ts-ioc-container
Version:
Fast, lightweight TypeScript dependency injection container with a clean API, scoped lifecycles, decorators, tokens, hooks, lazy injection, customizable providers, and no global container objects.
39 lines (38 loc) • 1.12 kB
JavaScript
import { InjectionToken } from './InjectionToken';
export class FunctionToken extends InjectionToken {
fn;
_getArgsFn;
_isLazy;
constructor(fn, { getArgsFn = (_, { args = [] } = {}) => args, isLazy = false } = {}) {
super();
this.fn = fn;
this._getArgsFn = getArgsFn;
this._isLazy = isLazy;
}
resolve(s, { args = [], lazy } = {}) {
return this.fn(s, {
args: this._getArgsFn(s, { args }),
lazy: this._isLazy || lazy,
});
}
args(...newArgs) {
const parentFn = this._getArgsFn;
return new FunctionToken(this.fn, {
getArgsFn: (s, opts) => [...parentFn(s, opts), ...newArgs],
isLazy: this._isLazy,
});
}
argsFn(fn) {
const parentFn = this._getArgsFn;
return new FunctionToken(this.fn, {
getArgsFn: (s, opts) => [...parentFn(s, opts), ...fn(s)],
isLazy: this._isLazy,
});
}
lazy() {
return new FunctionToken(this.fn, {
getArgsFn: this._getArgsFn,
isLazy: true,
});
}
}