Skip to content

Commit

Permalink
feat: alias factory option
Browse files Browse the repository at this point in the history
automatically set up aliases when registering a factory

closes #105
  • Loading branch information
Jack Ellis authored and jackmellis committed Dec 11, 2020
1 parent 2c75d0d commit de0a24c
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/__tests__/js/alias.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,13 @@ test('it throws when alias does not exist', t => {

t.throws(() => jpex.alias('foo', 'bah'));
});

test('aliases a factory at registration', t => {
const { jpex } = t.context;

jpex.factory('foo', [], () => 'foo', { alias: 'bah' });

const result = jpex.resolve('bah');

t.is(result, 'foo');
});
14 changes: 13 additions & 1 deletion src/__tests__/ts/alias.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,19 @@ test('it aliases two types', t => {

test('it throws when alias does not exist', t => {
const { jpex } = t.context;
type Foo = 'string';
type Foo = string;

t.throws(() => jpex.alias<Foo>('bah'));
});

test('aliases a factory at registration', t => {
const { jpex } = t.context;
type Foo = any;
type Bah = any;

jpex.factory<Foo>(() => 'foo', { alias: [ jpex.infer<Bah>() ] });

const result = jpex.resolve<Bah>();

t.is(result, 'foo');
});
6 changes: 5 additions & 1 deletion src/registers/factory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { JpexInstance, Factory, Dependency, AnyFunction, FactoryOpts } from '../types';
import { isString, isFunction, hasLength } from '../utils';
import { isString, isFunction, hasLength, ensureArray } from '../utils';

export const validateArgs = (name: string, dependencies: Dependency[], fn: AnyFunction) => {
if (!isString(name)) {
Expand Down Expand Up @@ -37,4 +37,8 @@ export default function factory <T>(
lifecycle: opts.lifecycle || this.$$config.lifecycle,
};
this.$$factories[name] = f;

if (opts.alias) {
ensureArray(opts.alias).forEach(alias => this.alias(alias, name));
}
}
1 change: 1 addition & 0 deletions src/types/JpexInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface SetupConfig {
export interface FactoryOpts {
lifecycle?: Lifecycle,
precedence?: Precedence,
alias?: string | string[],
}
export interface ServiceOpts extends FactoryOpts {
bindToInstance?: boolean,
Expand Down

0 comments on commit de0a24c

Please # to comment.