krispy
Version:
Basic synchronous dependency injector
56 lines • 2.47 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const InjectorType_1 = __importDefault(require("./enum/InjectorType"));
const UnresolvableDependencyException_1 = __importDefault(require("./exception/UnresolvableDependencyException"));
const CannotRegisterDependencyException_1 = __importDefault(require("./exception/CannotRegisterDependencyException"));
const UnexpectedStateException_1 = __importDefault(require("./exception/UnexpectedStateException"));
const InjectorUtil_1 = __importDefault(require("./util/InjectorUtil"));
class Injector {
static get global() {
if (!Injector._globalInjector) {
Injector._globalInjector = new Injector();
}
return Injector._globalInjector;
}
constructor() {
this._items = new WeakMap();
}
add(base, inherited, type) {
if (!InjectorUtil_1.default.isInheritedFrom(base, inherited)) {
throw new CannotRegisterDependencyException_1.default(`Class ${inherited.name} does not inherit from ${base.name}`);
}
this._items.set(base, { create: inherited, type });
}
addTransient(base, inherited) {
this.add(base, inherited, InjectorType_1.default.transient);
}
addSingleton(base, inherited) {
this.add(base, inherited, InjectorType_1.default.singleton);
}
resolve(base) {
if (!this._items.has(base)) {
throw new UnresolvableDependencyException_1.default(`Dependency ${base.name} is not registered`);
}
const item = this._items.get(base);
if (item == null) {
throw new UnresolvableDependencyException_1.default(`Registered dependency ${base.name} is null`);
}
if (item.type === InjectorType_1.default.transient) {
return new item.create();
}
if (item.type === InjectorType_1.default.singleton) {
if (item.instance) {
return item.instance;
}
const instance = new item.create();
item.instance = instance;
return instance;
}
throw new UnexpectedStateException_1.default(`Unexpected State: Injection type was ${item.type}`);
}
}
exports.default = Injector;
//# sourceMappingURL=Injector.js.map