UNPKG

@jable/inject

Version:

Inject dependencies into injectable classes

87 lines (86 loc) 2.64 kB
var Symbol = require('es6-symbol'); import { getName } from "./getName"; import { NameProperty } from "./constants"; export class InjectProvider { constructor() { this.injectables = {}; this.SYMBOL_ID = Symbol('Id'); } /** * Instance of InjectProvider * * @readonly * @static * @type {InjectProvider} * @memberOf InjectProvider */ static get Instance() { return this._instance || (this._instance = new this()); } /** * Check a class for a symbol id * * @param {NewableType<any>} instanceType Class to check for Id * @returns {boolean} */ hasId(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 */ getId(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 */ setName(namespace, instanceType) { instanceType[NameProperty] = (namespace != '' ? namespace + '.' : '') + 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 */ get(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 */ register(instanceType, key) { if (key == null) { key = instanceType[this.SYMBOL_ID] || Symbol(getName(instanceType)); } instanceType[this.SYMBOL_ID] = key; this.injectables[key] = instanceType; } }