UNPKG

@analog-tools/inject

Version:

Dependency injection for AnalogJS server-side applications

118 lines (117 loc) 3.2 kB
let s = null; function r() { return s || (s = new a()), s; } class a { constructor() { this.serviceMap = /* @__PURE__ */ new Map(); } /** * Register a service with a token * @param token - The injection token for the service * @param properties - The constructor parameters for the service class */ register(e, ...t) { if (this.isServiceInjectable(e) && (!this.hasService(e) || this.getService(e) === void 0)) { if (t === void 0 || t.length === 0) { this.serviceMap.set(this.getInjcectableName(e), new e()); return; } this.serviceMap.set( this.getInjcectableName(e), new e(...t) ); } } registerAsUndefined(e) { if (this.isServiceInjectable(e)) this.serviceMap.set(this.getInjcectableName(e), void 0); else throw new Error( `Service with token ${this.getInjcectableName( e )} is not injectable. Ensure it has the INJECTABLE static property set to true.` ); } registerCustomServiceInstance(e, t) { if (this.isServiceInjectable(e)) this.serviceMap.set(this.getInjcectableName(e), t); else throw new Error( `Service with token ${this.getInjcectableName( e )} is not injectable. Ensure it has the INJECTABLE static property set to true.` ); } /** * Get a service by its token * @param token - The injection token for the service * @returns The requested service or undefined if not found */ getService(e) { if (this.isServiceInjectable(e)) return this.hasService(e) || this.register(e), this.serviceMap.get(this.getInjcectableName(e)); } /** * Check if a service is registered * @param token - The injection token for the service * @returns True if the service is registered */ hasService(e) { return this.serviceMap.has(this.getInjcectableName(e)); } /** * Check if a service class is injectable * @param token - The injection token for the service * @returns True if the service has the INJECTABLE static property set to true */ isServiceInjectable(e) { const t = e.INJECTABLE; return t !== void 0 && t !== !1; } getInjcectableName(e) { if (this.isServiceInjectable(e)) { const t = e.INJECTABLE; return typeof t != "string" ? e.name : t; } throw new Error( `Service with token ${e.name} is not injectable. Ensure it has the INJECTABLE static property set to true.` ); } /** * Clean up all services when the game is being destroyed */ destroy() { this.serviceMap.clear(); } } function h(i, e, t = {}) { const { required: n = !0 } = t, c = i.getService(e); if (!c && n) throw new Error( `Service with token ${e || "unknown"} not found in registry` ); return c; } function v(i, e = {}) { return h(r(), i, e); } function o(i, ...e) { r().register(i, ...e); } function u(i) { r().registerAsUndefined(i); } function l(i, e) { r().registerCustomServiceInstance(i, e); } function g() { r().destroy(); } export { v as inject, l as registerMockService, o as registerService, u as registerServiceAsUndefined, g as resetAllInjections };