-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServiceStorage.ts
48 lines (38 loc) · 1.34 KB
/
ServiceStorage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
interface GenericConstructor {
new (...args: Array<unknown>): unknown;
}
export class ServicesMap {
private readonly classes = new Map<
GenericConstructor,
Array<GenericConstructor>
>();
private readonly instances = new Map<GenericConstructor, unknown>();
// deno-lint-ignore no-explicit-any
public provides<T extends Array<any>>(
service: { new (...args: T): unknown },
// deno-lint-ignore no-explicit-any
deps: Array<{ new (...args: Array<any>): unknown }>
) {
this.classes.set(service as GenericConstructor, deps);
}
// deno-lint-ignore no-explicit-any
public resolve<C extends new (...args: Array<any>) => unknown>(
Service: C
): InstanceType<C> {
const instantiatedService = this.instances.get(
Service as GenericConstructor
);
if (instantiatedService) return instantiatedService as InstanceType<C>;
const serviceDeps = this.classes.get(Service as GenericConstructor);
if (!serviceDeps) {
throw new Error("Some deps were not registered");
}
const depsInstances = serviceDeps.map((Dependency) => {
return this.resolve(Dependency);
});
const newInstance = new Service(...depsInstances);
this.instances.set(Service as GenericConstructor, newInstance);
return newInstance as InstanceType<C>;
}
}
export const serviceMapSingleton = new ServicesMap();