@wocker/core
Version:
Core of the Wocker
62 lines (61 loc) • 2.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstanceWrapper = void 0;
const env_1 = require("../env");
class InstanceWrapper {
constructor(module, provider) {
this.module = module;
this.provider = provider;
const [token, type, instance] = this.normalizeProvider(provider);
this._token = token;
this._type = type;
this._instance = instance;
}
normalizeProvider(provider) {
if (provider && typeof provider === "object") {
if ("provide" in provider && "useValue" in provider) {
return [provider.provide, null, provider.useValue];
}
if ("provide" in provider && "useClass" in provider) {
return [provider.provide, provider.useClass, null];
}
}
return [
Reflect.getMetadata(env_1.INJECT_TOKEN_METADATA, provider) || provider,
provider,
null
];
}
get type() {
return this._type;
}
get token() {
return this._token;
}
get instance() {
if (!this._instance) {
if (!this._type) {
throw new Error("Type not defined");
}
const types = Reflect.getMetadata(env_1.PARAMTYPES_METADATA, this._type) || [];
const selfTypes = Reflect.getMetadata(env_1.SELF_DECLARED_DEPS_METADATA, this._type) || [];
if (selfTypes.length > 0) {
selfTypes.forEach(({ index, token }) => {
types[index] = token;
});
}
const params = types.map((type) => {
return this.module.get(type);
});
this._instance = new this._type(...params);
}
return this._instance;
}
replace(provider) {
const [token, type, instance] = this.normalizeProvider(provider);
this._token = token;
this._type = type;
this._instance = instance;
}
}
exports.InstanceWrapper = InstanceWrapper;