@blynx/inject
Version:
Dependency injector for javascript
94 lines (93 loc) • 3.1 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var Symbol = require('es6-symbol');
var getName_1 = require("./getName");
var constants_1 = require("./constants");
var InjectProvider = /** @class */ (function () {
function InjectProvider() {
this.injectables = {};
this.SYMBOL_ID = Symbol('Id');
}
Object.defineProperty(InjectProvider, "Instance", {
/**
* Instance of InjectProvider
*
* @readonly
* @static
* @type {InjectProvider}
* @memberOf InjectProvider
*/
get: function () {
return this._instance || (this._instance = new this());
},
enumerable: true,
configurable: true
});
/**
* Check a class for a symbol id
*
* @param {NewableType<any>} instanceType Class to check for Id
* @returns {boolean}
*/
InjectProvider.prototype.hasId = function (instanceType) {
return this.getId(instanceType) != null;
};
/**
* Get a classes symbol id
*
* @param {NewableType<any>} instanceType Class to get symbol id for
* @returns {Symbol} Symbol id of the class
*
* @memberOf InjectProvider
*/
InjectProvider.prototype.getId = function (instanceType) {
return instanceType[this.SYMBOL_ID];
};
/**
* Set the name a of a newable type
*
* @param {string} namespace Namespace to prepend
* @param {NewableType<any>} instanceType Newable instance type
*
* @memberOf InjectProvider
*/
InjectProvider.prototype.setName = function (namespace, instanceType) {
instanceType[constants_1.NameProperty] = (namespace != '' ? namespace + '.' : '') + getName_1.getName(instanceType);
};
/**
* Get an instance of an injectable
*
* @template T Type of instance
* @param {NewableType<any>} instanceType Instance type to get
* @returns Instance of injectable or null
*
* @memberOf InjectProvider
*/
InjectProvider.prototype.get = function (instanceType) {
var key = instanceType[this.SYMBOL_ID];
if (this.injectables[key] != null) {
if (typeof this.injectables[key] === 'function') {
return this.injectables[key] = new (this.injectables[key])();
}
return this.injectables[key];
}
return null;
};
/**
* Register an injectable
*
* @template T Type of injectable
* @param {NewableType<T>} instanceType Instance type to create
* @param {Symbol?} key Unique ID for instance. Use when defining a new constructor for an existing injectable
*
* @memberOf InjectProvider
*/
InjectProvider.prototype.register = function (instanceType, key) {
if (key == null) {
key = instanceType[this.SYMBOL_ID] || Symbol(getName_1.getName(instanceType));
}
instanceType[this.SYMBOL_ID] = key;
this.injectables[key] = instanceType;
};
return InjectProvider;
}());
exports.InjectProvider = InjectProvider;