forked from guiseek/nx-clean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinjector.ts
75 lines (57 loc) · 1.76 KB
/
injector.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
type Constructor = new (...params: unknown[]) => void;
/**
* PRIMEIRA POC
* @deprecated
*/
export interface FactorySansProvider {
useFactory: Function;
deps?: any[];
}
export interface FactoryProvider extends FactorySansProvider {
provide: any;
multi?: boolean;
}
export type Provider = FactoryProvider | Constructor;
export class Injector {
private static instance: Injector;
private _container = new Map();
private constructor(private _providers: Provider[]) {
this._providers.forEach((provider) => {
const factory = provider as FactoryProvider;
if (factory.provide && factory.useFactory) {
const { provide, useFactory, deps = [] } = factory;
const getDependency = (dependency: Constructor) => {
const dep = this.get(dependency);
return dep ? dep : new dependency();
};
const dependencies = deps.length > 0 ? deps.map(getDependency) : [];
this._container.set(provide, useFactory(...dependencies));
} else {
this._providers.forEach((provider) => {
this._container.set(provider, new (provider as Constructor)());
});
}
});
}
static create(_providers: Provider[]) {
if (!Injector.instance) {
Injector.instance = new Injector(_providers);
}
return Injector.instance;
}
get<T>(token: FactoryProvider['provide']) {
const instance = this._container.get(token) as T;
if (!instance) {
throw Error('No provider instance');
}
return instance;
}
public static getInstance(): Injector {
if (!Injector.instance) {
Injector.instance = new Injector([]);
}
return Injector.instance;
}
}