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.
45 lines (44 loc) • 1.25 kB
JavaScript
import { InjectionToken } from './InjectionToken';
export class SingleToken extends InjectionToken {
token;
_getArgsFn;
_isLazy;
constructor(token, { getArgsFn = () => [], isLazy = false } = {}) {
super();
this.token = token;
this._getArgsFn = getArgsFn;
this._isLazy = isLazy;
}
select(fn) {
return (s) => fn(this.resolve(s));
}
resolve(s, { args = [], lazy } = {}) {
return s.resolve(this.token, {
args: this._getArgsFn(s, { args }),
lazy: this._isLazy || lazy,
});
}
bindTo(r) {
r.bindToKey(this.token);
}
args(...newArgs) {
const parentFn = this._getArgsFn;
return new SingleToken(this.token, {
getArgsFn: (s, opts) => [...parentFn(s, opts), ...newArgs],
isLazy: this._isLazy,
});
}
argsFn(fn) {
const parentFn = this._getArgsFn;
return new SingleToken(this.token, {
getArgsFn: (s, opts) => [...parentFn(s, opts), ...fn(s)],
isLazy: this._isLazy,
});
}
lazy() {
return new SingleToken(this.token, {
getArgsFn: this._getArgsFn,
isLazy: true,
});
}
}