@snow-tzu/type-config
Version:
Core configuration management system with Spring Boot-like features
65 lines (64 loc) • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Container = void 0;
require("reflect-metadata");
const decorators_1 = require("./decorators");
class Container {
constructor() {
this.instances = new Map();
}
setConfigManager(configManager) {
this.configManager = configManager;
}
registerConfig(ConfigClass) {
if (!this.configManager) {
throw new Error('ConfigManager not set in container');
}
const instance = this.configManager.bind(ConfigClass);
this.instances.set(ConfigClass, instance);
}
register(ServiceClass) {
if (!Reflect.getMetadata(decorators_1.INJECTABLE_KEY, ServiceClass)) {
throw new Error(`Class ${ServiceClass.name} must be decorated with @Injectable`);
}
}
registerInstance(token, instance) {
this.instances.set(token, instance);
}
has(token) {
return this.instances.has(token);
}
resolve(target) {
if (this.instances.has(target)) {
return this.instances.get(target);
}
const paramTypes = Reflect.getMetadata('design:paramtypes', target) || [];
const injections = Reflect.getMetadata(decorators_1.INJECT_KEY, target) || [];
const dependencies = paramTypes.map((paramType, index) => {
const token = injections[index] || paramType;
if (Reflect.getMetadata(decorators_1.CONFIG_PREFIX_KEY, token)) {
if (!this.instances.has(token)) {
this.registerConfig(token);
}
return this.instances.get(token);
}
return this.resolve(token);
});
const instance = new target(...dependencies);
this.instances.set(target, instance);
return instance;
}
get(token) {
if (typeof token === 'function') {
return this.resolve(token);
}
if (this.instances.has(token)) {
return this.instances.get(token);
}
throw new Error(`No provider found for token: ${String(token)}`);
}
clear() {
this.instances.clear();
}
}
exports.Container = Container;