UNPKG

sahara

Version:

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

53 lines 1.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ObjectBuilder = void 0; const event_emitter_1 = require("./event-emitter"); function getParams(typeInfo) { const params = typeInfo.args; params.sort(function (a, b) { if (a.position === b.position) { return 0; } return a.position < b.position ? -1 : 1; }); return params; } const isConstructable = (fn, typeInfo) => { return typeInfo.constructable; }; class ObjectBuilder extends event_emitter_1.EventEmitter { constructor(resolvable) { super(); this.resolvable = resolvable; } buildObject(typeInfo, args) { const ctor = typeInfo.ctor; if (isConstructable(ctor, typeInfo)) { return new ctor(...args); } throw new Error(`Unable to construct class from type ${typeInfo.name}`); } newInstanceSync(typeInfo, context) { this.emit('building', typeInfo); const args = getParams(typeInfo).map((typeData) => { return this.resolvable.resolveSync(typeData.type, context); }); const instance = this.buildObject(typeInfo, args); this.emit('built', typeInfo, instance); return instance; } async newInstance(typeInfo, context) { this.emit('building', typeInfo); const args = []; const params = getParams(typeInfo); // NOTE: these must be resolved in order for (const param of params) { args.push(await this.resolvable.resolve(param.type, context)); } const instance = this.buildObject(typeInfo, args); this.emit('built', typeInfo, instance); return instance; } } exports.ObjectBuilder = ObjectBuilder; //# sourceMappingURL=object-builder.js.map