Last active
June 28, 2022 09:38
-
-
Save kaplan81/d706bcb7cd8643b1db9d2f2b00b2c381 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Constructor } from '../../models/constructor.model'; | |
import { isWindow } from '../../utils/window/window.util'; | |
/** | |
* // constructor.model.ts | |
* export type Constructor<T = unknown> = new (...args: any[]) => T; | |
* | |
* // window.util.ts | |
* export const isWindow = (element: typeof globalThis | Window | HTMLElement | null): boolean => { | |
* return element !== null | |
* ? typeof window !== 'undefined' && Object.prototype.hasOwnProperty.call(element, 'self') | |
* : false; | |
* | |
* // provider.model.ts | |
* export interface EnvironmentInjectorProvider { | |
* instances: Map<string, any>; | |
* provideInstance(key: string, instance: any): void; | |
* } | |
* | |
* @example | |
* export interface AppComponent extends EnvironmentInjectorProvider {} | |
* @Provider() | |
* @Component({ | |
* selector: 'app-root', | |
* templateUrl: './app.component.html', | |
* }) | |
* export class AppComponent implements OnInit { | |
* [...] | |
*/ | |
export const Provider = (): ((c: Constructor) => void) => { | |
return (providerConstructor: Constructor) => { | |
/** | |
* By default these properties are configurable = enumerable = writable = false | |
*/ | |
Object.defineProperty(providerConstructor.prototype, 'instances', { | |
value: new Map<string, any>(), | |
}); | |
if (isWindow(globalThis)) { | |
globalThis.addEventListener('request-instance', (event: Event) => { | |
const key: string = (event as CustomEvent).detail.key; | |
if ((providerConstructor.prototype.instances as Map<string, any>).has(key)) { | |
(event as CustomEvent).detail.instance = ( | |
providerConstructor.prototype.instances as Map<string, any> | |
).get(key); | |
event.stopPropagation(); | |
} | |
}); | |
} else { | |
throw Error('globalThis must be Window'); | |
} | |
providerConstructor.prototype.provideInstance = function (key: string, instance: any): void { | |
(providerConstructor.prototype.instances as Map<string, any>).set(key, instance); | |
}; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment