UNPKG

@micro.ts/core

Version:

Microservice framework with Typescript

105 lines (104 loc) 3.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContainerRegistry = exports.DiRegistry = exports.RegistryToken = void 0; const DiOptionsTypes_1 = require("./types/DiOptionsTypes"); class RegistryToken { constructor(name) { this.name = name; } } exports.RegistryToken = RegistryToken; class DiRegistry { constructor() { /** * Store service metadata */ this.serviceOptions = new Map(); /** * Store resolvers metadata and resolver functions */ this.resolvers = new Map(); } /** * Verify for circular dependencies * @param key * @param visited */ verify(key, searchKey, visited = new Map()) { var _a; if (typeof key === "string") { return; } if (searchKey === key && visited.has(searchKey)) { throw new Error(`Circular dependency found for [${key}]!`); } if (visited.has(searchKey)) { return; } visited.set(searchKey, true); const metadata = this.getMetadata(searchKey); if (!!metadata) { const ctorParams = metadata.ctorParams || []; for (const item of ctorParams) { const newKey = ((_a = item.injectOptions) === null || _a === void 0 ? void 0 : _a.key) || item.type; this.verify(key, newKey, visited); } } } /** * Bind a key to a constructor function * @param key * @param options */ bind(key, options) { if (!options.scope) { options.scope = DiOptionsTypes_1.ServiceScope.Transient; } this.serviceOptions.set(key, options); this.verify(key, key); } /** * Bind a key to a given resolver function * @param key * @param resolver * @param scope */ bindResolver(key, resolver, scope = DiOptionsTypes_1.ServiceScope.Transient) { this.resolvers.set(key, { resolver, scope }); } /** * Check if a resolver exists for a given key * @param key */ hasResolver(key) { return this.resolvers.has(key); } /** * Get stored metadata for a given key * @param key */ getMetadata(key) { return this.serviceOptions.get(key); } /** * Return resolver information and resolving function * @param key */ getResolver(key) { return this.resolvers.get(key); } /** * Default metadata if they are not specified * @param key */ initializeMetadata(key) { const constructorArgs = Reflect.getOwnMetadata('design:injectparamtypes', key) || []; const options = {}; options.ctorParams = constructorArgs; options.scope = DiOptionsTypes_1.ServiceScope.Singleton; this.serviceOptions.set(key, options); return options; } } exports.DiRegistry = DiRegistry; exports.ContainerRegistry = new DiRegistry();