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.
35 lines (34 loc) • 933 B
JavaScript
const proxyStateMap = new WeakMap();
const unwrapProxyTarget = (value) => {
return isProxy(value) ? getProxyTarget(value) : value;
};
export function isProxy(value) {
return proxyStateMap.has(value);
}
export function getProxyTarget(value) {
return proxyStateMap.get(value).getTarget();
}
export 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;
}
export function toLazyIf(resolveInstance, isLazy = false) {
if (isLazy) {
return lazyProxy(resolveInstance);
}
return resolveInstance();
}