@analog-tools/inject
Version:
Dependency injection for AnalogJS server-side applications
2 lines (1 loc) • 1.99 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});let s=null;function r(){return s||(s=new a),s}class a{constructor(){this.serviceMap=new Map}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.`)}getService(e){if(this.isServiceInjectable(e))return this.hasService(e)||this.register(e),this.serviceMap.get(this.getInjcectableName(e))}hasService(e){return this.serviceMap.has(this.getInjcectableName(e))}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.`)}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 l(i){r().registerAsUndefined(i)}function g(i,e){r().registerCustomServiceInstance(i,e)}function u(){r().destroy()}exports.inject=v;exports.registerMockService=g;exports.registerService=o;exports.registerServiceAsUndefined=l;exports.resetAllInjections=u;