UNPKG

ts-ioc-container

Version:

Fast, lightweight TypeScript dependency injection container with a clean API, scoped lifecycles, decorators, tokens, hooks, lazy injection, customizable providers, and no global container objects.

41 lines (40 loc) 1.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isProxy = isProxy; exports.getProxyTarget = getProxyTarget; exports.lazyProxy = lazyProxy; exports.toLazyIf = toLazyIf; const proxyStateMap = new WeakMap(); const unwrapProxyTarget = (value) => { return isProxy(value) ? getProxyTarget(value) : value; }; function isProxy(value) { return proxyStateMap.has(value); } function getProxyTarget(value) { return proxyStateMap.get(value).getTarget(); } function lazyProxy(resolveInstance) { let instance; const state = { getTarget: () => { instance = instance ?? unwrapProxyTarget(resolveInstance()); return instance; }, }; const proxy = new Proxy({}, { get: (_, prop) => { const target = state.getTarget(); // @ts-ignore return target[prop]; }, }); proxyStateMap.set(proxy, state); return proxy; } function toLazyIf(resolveInstance, isLazy = false) { if (isLazy) { return lazyProxy(resolveInstance); } return resolveInstance(); }