diff --git a/src/__tests__/js/alias.test.ts b/src/__tests__/js/alias.test.ts index e9e6bda..1b5c703 100644 --- a/src/__tests__/js/alias.test.ts +++ b/src/__tests__/js/alias.test.ts @@ -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'); +}); diff --git a/src/__tests__/ts/alias.test.ts b/src/__tests__/ts/alias.test.ts index 9954aef..f961a15 100644 --- a/src/__tests__/ts/alias.test.ts +++ b/src/__tests__/ts/alias.test.ts @@ -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('bah')); }); + +test('aliases a factory at registration', t => { + const { jpex } = t.context; + type Foo = any; + type Bah = any; + + jpex.factory(() => 'foo', { alias: [ jpex.infer() ] }); + + const result = jpex.resolve(); + + t.is(result, 'foo'); +}); diff --git a/src/registers/factory.ts b/src/registers/factory.ts index 903c68e..5ab3684 100644 --- a/src/registers/factory.ts +++ b/src/registers/factory.ts @@ -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)) { @@ -37,4 +37,8 @@ export default function factory ( lifecycle: opts.lifecycle || this.$$config.lifecycle, }; this.$$factories[name] = f; + + if (opts.alias) { + ensureArray(opts.alias).forEach(alias => this.alias(alias, name)); + } } diff --git a/src/types/JpexInstance.ts b/src/types/JpexInstance.ts index 7003ef8..2108767 100644 --- a/src/types/JpexInstance.ts +++ b/src/types/JpexInstance.ts @@ -21,6 +21,7 @@ export interface SetupConfig { export interface FactoryOpts { lifecycle?: Lifecycle, precedence?: Precedence, + alias?: string | string[], } export interface ServiceOpts extends FactoryOpts { bindToInstance?: boolean,