ts-ioc-container
Version:
Typescript IoC container
45 lines (44 loc) • 1.3 kB
JavaScript
import { pipe, toLazyIf } from '../utils';
import { isProviderPipe } from './ProviderPipe';
export class Provider {
resolveDependency;
static fromClass(Target) {
return new Provider((container, options) => container.resolveClass(Target, options));
}
static fromValue(value) {
return new Provider(() => value);
}
static fromKey(key) {
return new Provider((c) => c.resolveOne(key));
}
argsFn = () => [];
checkAccess = () => true;
isLazy = false;
constructor(resolveDependency) {
this.resolveDependency = resolveDependency;
}
pipe(...mappers) {
const fns = mappers.map((m) => (isProviderPipe(m) ? m.mapProvider.bind(m) : m));
return pipe(...fns)(this);
}
resolve(container, { args = [], lazy } = {}) {
return toLazyIf(() => this.resolveDependency(container, {
args: [...this.argsFn(container, ...args), ...args],
}), lazy ?? this.isLazy);
}
setAccessPredicate(predicate) {
this.checkAccess = predicate;
return this;
}
lazy() {
this.isLazy = true;
return this;
}
setArgs(argsFn) {
this.argsFn = argsFn;
return this;
}
hasAccess(options) {
return this.checkAccess(options);
}
}