tedi
Version:
Express wrappper written in typescript with dependency injection capabilities
108 lines (107 loc) • 3.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const lodash_1 = require("lodash");
const di_1 = require("./di");
const tedi_error_1 = require("./tedi-error");
const utils_1 = require("./utils");
class ModuleError extends tedi_error_1.TediError {
constructor(target, msg, error) {
super(`${utils_1.getClassName(target)}: ${msg}`, error);
}
}
exports.ModuleError = ModuleError;
function validateModule(instance) {
// check if it was valid metadata
if (!(instance instanceof Module)) {
throw new ModuleError(instance, `must be an instance of ${utils_1.getClassName(Module)}`);
}
}
exports.validateModule = validateModule;
exports.JSON_ROUTES = "JSON_ROUTES";
class Module {
constructor() {
this._parentModule = null;
this._di = new di_1.DIModule();
}
__setParent(module) {
this._parentModule = module;
this._di.__setParent(module._di);
}
getDIContainer() {
return this._di.getDIContainer();
}
getParentModule() {
return this._parentModule;
}
dependencies(...args) {
// normalize dependecies and iterate
(lodash_1.isArray(args) ? args : []).forEach((dep) => {
this.setDependency(dep);
});
return this;
}
setDependency(dep) {
if (lodash_1.isUndefined(dep) || lodash_1.isNull(dep)) {
return this;
}
else if (lodash_1.isArray(dep)) {
dep.forEach(aDep => this.setDependency(aDep));
}
else if (!(dep instanceof di_1.DependencyInfo)) {
this._di.setDependency(di_1.dependency(dep));
}
else {
this._di.setDependency(dep);
}
return this;
}
getDependency(token) {
// let depInstance = this._getBindingRecursively<T>(token);
let depInstance;
try {
depInstance = this._getBinding(token);
}
catch (error) {
throw new ModuleError(this, `Error loading dependency for token ${di_1.getTokenDescription(token)}`, error);
}
if (!depInstance) {
throw new ModuleError(this, `Could not find dependency "${di_1.getTokenDescription(token)}" in the module tree`, null);
}
return depInstance;
}
hasDependency(token) {
return this._di.hasDependency(token);
}
setModule(token, module) {
if (!(module instanceof Module)) {
throw new ModuleError(this, `Expected a Module instance`, null);
}
// initialize module
module.__setParent(this);
// set dependency
this.setDependency(di_1.dependency(token, { value: module }));
return this;
}
setJsonRoutes(value) {
this._di.setDependency(di_1.dependency(exports.JSON_ROUTES, { value: value }));
return this;
}
getJsonRoutes() {
return this._di.getDependency(exports.JSON_ROUTES);
}
snapshot() {
this._di.snapshot();
return this;
}
restore() {
this._di.restore();
return this;
}
_getBinding(token) {
return this._di.hasDependency(token) ?
this._di.getDependency(token) :
null;
}
}
exports.Module = Module;