UNPKG

ts-ioc-container

Version:
73 lines (72 loc) 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Registration = void 0; const utils_1 = require("../utils"); const Provider_1 = require("../provider/Provider"); const DependencyMissingKeyError_1 = require("../errors/DependencyMissingKeyError"); const IRegistration_1 = require("./IRegistration"); const ProviderPipe_1 = require("../provider/ProviderPipe"); class Registration { createProvider; key; scopePredicates; static fromClass(Target) { const transform = (0, utils_1.pipe)(...(0, IRegistration_1.getTransformers)(Target)); return transform(new Registration(() => Provider_1.Provider.fromClass(Target), Target.name)); } static fromValue(value) { if ((0, utils_1.isConstructor)(value)) { const transform = (0, utils_1.pipe)(...(0, IRegistration_1.getTransformers)(value)); return transform(new Registration(() => Provider_1.Provider.fromValue(value), value.name)); } return new Registration(() => Provider_1.Provider.fromValue(value)); } static fromFn(fn) { return new Registration(() => new Provider_1.Provider(fn)); } static fromKey(key) { return new Registration(() => Provider_1.Provider.fromKey(key)); } mappers = []; aliases = new Set(); constructor(createProvider, key, scopePredicates = []) { this.createProvider = createProvider; this.key = key; this.scopePredicates = scopePredicates; } bindToKey(key) { this.key = key; return this; } bindToAlias(alias) { this.aliases.add(alias); return this; } pipe(...mappers) { const fns = mappers.map((m) => ((0, ProviderPipe_1.isProviderPipe)(m) ? m.mapProvider.bind(m) : m)); this.mappers.push(...fns); return this; } when(...predicates) { this.scopePredicates.push(...predicates); return this; } matchScope(container) { if (this.scopePredicates.length === 0) { return true; } const [first, ...rest] = this.scopePredicates; return rest.reduce((prev, curr) => curr(container, prev), first(container)); } applyTo(container) { if (!this.matchScope(container)) { return; } if (!this.key) { throw new DependencyMissingKeyError_1.DependencyMissingKeyError('No key provided for registration'); } const provider = this.createProvider(); container.register(this.key, provider.pipe(...this.mappers), { aliases: [...this.aliases] }); } } exports.Registration = Registration;