UNPKG

sahara

Version:

An inversion-of-control container for managing dependencies. Supports constructor, property and method injection

76 lines 2.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MethodInjection = exports.PropertyInjection = exports.PropertyValueInjection = void 0; const util = require("./util"); const createContext = (object, suffix, type) => { var _a; const ctorName = ((_a = object === null || object === void 0 ? void 0 : object.constructor) === null || _a === void 0 ? void 0 : _a.name) || '?'; return { history: [{ name: `${ctorName}.${suffix}` + (type === 'MethodInjection' ? '()' : ''), type, }], }; }; class PropertyValueInjection { constructor(propertyName, value) { this.propertyName = propertyName; this.value = value; } async inject(object, container) { this.injectSync(object, container); } injectSync(object, container) { object[this.propertyName] = this.value; } } exports.PropertyValueInjection = PropertyValueInjection; class PropertyInjection { constructor(propertyName, valueKey) { this.propertyName = propertyName; this.valueKey = valueKey; } async inject(object, container) { const context = createContext(object, this.propertyName, 'PropertyInjection'); object[this.propertyName] = await container.resolve(this.valueKey, context); } injectSync(object, container) { const context = createContext(object, this.propertyName, 'PropertyInjection'); object[this.propertyName] = container.resolveSync(this.valueKey, context); } } exports.PropertyInjection = PropertyInjection; class MethodInjection { constructor(methodName, args) { this.methodName = methodName; this.args = args; } createError() { return new Error('Cannot perform method injection because the object does ' + `not have a method "${this.methodName}"`); } async inject(object, container) { const method = object[this.methodName]; if (!method || typeof (method) !== 'function') { throw this.createError(); } const context = createContext(object, this.methodName, 'MethodInjection'); const args = this.args || await Promise.all(util.getTypeInfo(method, '$__', 'method') .args .map(argInfo => container.resolve(argInfo.type, context))); method.call(object, ...args); } injectSync(object, container) { const method = object[this.methodName]; if (!method || typeof (method) !== 'function') { throw this.createError(); } const context = createContext(object, this.methodName, 'MethodInjection'); const args = this.args || util.getTypeInfo(method, '$__', 'method') .args .map(argInfo => container.resolveSync(argInfo.type, context)); method.call(object, ...args); } } exports.MethodInjection = MethodInjection; //# sourceMappingURL=injection.js.map