UNPKG

reactant-di

Version:

A dependency injection lib for Reactant

57 lines (54 loc) 1.46 kB
import 'reflect-metadata'; import { decorate, optional as optional$1 } from 'inversify'; import { inject } from './inject.js'; import { METADATA_KEY } from '../constants.js'; import { setMetadata } from '../util.js'; /** * ## Description * * You can use `@optional()` to decorate an optionally injected module. * * If other modules have no relevant dependency injection or are also optionally injected, the module will not be injected by default unless the injected module is imported in the `modules` parameter. * * ## Example * * ```ts * @injectable() * class Bar { * getValue() { * return 'bar'; * } * } * * @injectable() * class Foo { * getValue() { * return 'foo'; * } * } * * @injectable() * class FooBar { * constructor(@optional() public bar: Bar, @optional('foo') public foo: Foo) {} * } * * const fooBar = testBed({ * modules: [ * { provide: 'foo', useClass: Foo }, * ], * main: FooBar, * }); * * expect(fooBar.instance.foo.getValue()).toBe('foo'); * expect(fooBar.fooBar.bar).toBeUndefined(); * ``` */ function optional(serviceIdentifier) { return function (target, key, index) { var paramtypes = Reflect.getMetadata(METADATA_KEY.paramtypes, target); setMetadata(METADATA_KEY.optional, paramtypes[index], serviceIdentifier); decorate(inject(serviceIdentifier), target, index); decorate(optional$1(), target, index); }; } export { optional };