UNPKG

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.

86 lines (85 loc) 3.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Registration = void 0; const IContainer_1 = require("../container/IContainer"); const Provider_1 = require("../provider/Provider"); const DependencyMissingKeyError_1 = require("../errors/DependencyMissingKeyError"); const IRegistration_1 = require("./IRegistration"); const IRegistration_2 = require("./IRegistration"); const SingleToken_1 = require("../token/SingleToken"); const fp_1 = require("../utils/fp"); const basic_1 = require("../utils/basic"); class Registration { createProvider; key; scopeRules; static fromClass(Target, { name } = {}) { const transform = (0, fp_1.pipe)(...(0, IRegistration_2.getTransformers)(Target)); return transform(new Registration(() => Provider_1.Provider.fromClass(Target), name ?? Target.name)); } static fromValue(value) { if (basic_1.Is.constructor(value)) { const transform = (0, fp_1.pipe)(...(0, IRegistration_2.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, scopeRules = []) { this.createProvider = createProvider; this.key = key; this.scopeRules = scopeRules; } bindToKey(key) { this.key = key; return this; } bindToAlias(alias) { this.aliases.add(alias); return this; } pipe(...mappers) { const fns = mappers.map((m) => ((0, IRegistration_1.isProviderPipe)(m) ? m.mapProvider.bind(m) : m)); this.mappers.push(...fns); return this; } when(...predicates) { this.scopeRules.push(...predicates); return this; } bindTo(key) { if ((0, IContainer_1.isDependencyKey)(key)) { new SingleToken_1.SingleToken(key).bindTo(this); return this; } key.bindTo(this); return this; } matchScope(container) { return this.scopeRules.reduce((prev, curr) => curr(container, prev), true); } applyTo(container) { if (!this.matchScope(container)) { return; } if (!this.key) { throw new DependencyMissingKeyError_1.DependencyMissingKeyError('No key provided for registration'); } const provider = this.mappers.reduce((p, m) => m(p), this.createProvider()); container.register(this.key, provider, { aliases: [...this.aliases] }); } getKeyOrFail() { if (!this.key) { throw new DependencyMissingKeyError_1.DependencyMissingKeyError('No key provided for registration'); } return this.key; } } exports.Registration = Registration;