-
Notifications
You must be signed in to change notification settings - Fork 0
/
Injector.ts
212 lines (193 loc) · 6.45 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { Binder } from './Binder'
import {
createProvider,
getProviderName,
isProvider,
Provider,
ProviderValueType
} from './Provider'
import { InjectorsStack } from './InjectorsStack'
/**
* Thrown when circular dependency is detected
*/
export class CircularDependencyError extends Error {
constructor (providers: Array<Provider<unknown>>) {
const providerNames = providers.map(getProviderName)
.map((name) => name ?? '?')
super(`Circular dependency detected: ${providerNames.join('->')}`)
}
}
export class NoBinderError extends Error {
constructor (provider: Provider<unknown>) {
const providerName = getProviderName(provider) ?? 'unknown'
super(`Value of ${providerName} provider is not found`)
}
}
// https://stackoverflow.com/a/50375286
type UnionToIntersection<T> =
(T extends any ? (k: T) => void : never) extends (k: infer R) => void ? R : never
/**
* Provider which every injector binds itself to
*/
export const $Injector = createProvider<Injector>()
/**
* Main entity in the library, which holds provider's bindings and through which
* dependencies are resolved
*/
export class Injector {
private readonly binders = new Map<() => unknown, Binder<unknown>>()
private readonly resolvingProviders: Array<Provider<unknown>> = []
private readonly name: string | undefined
private readonly parent: Injector | undefined
private readonly logger: (msg: string) => unknown
/**
* @param params.name name of the injector which can be useful mainly for debugging purposes
* @param params.parent parent injector for the composition of injectors
* @param params.logger specific log function if the custom output is required
*/
constructor (params: {
name?: string
parent?: Injector
logger?: (msg: string) => unknown
} = {}) {
const { name, parent, logger = console.warn } = params
this.name = name
this.parent = parent
this.logger = logger
this.bindProvider($Injector).toValue(this)
}
/**
* Creates new binder and joins it to the specified providers. If the provider
* is already bound, then overriding occurs
* @param providers providers which the binder should be joined to
*/
bindProvider<
ProviderT extends Array<Provider<unknown>>,
ValueT extends UnionToIntersection<ProviderT extends Array<Provider<infer R>> ? R : never>
>(...providers: ProviderT): Binder<ValueT> {
const binder = new Binder<ValueT>(this)
providers.forEach((provider) => this.binders.set(provider, binder))
return binder
}
/**
* Resolves all providers to their values and assigns them to the specified instance
* @param instance
* @param providers
*/
injectValues<T extends object, K extends keyof T>(
instance: T,
providers: Record<K, Provider<T[K]>>
): void {
Object.entries(providers)
.filter(([, value]) => isProvider(value))
.forEach(([name, provider]: [string, Provider<T[K]>]) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
instance[name] = this.getValue(provider)
})
}
/**
* Activates this injector and creates new instance of the type with the provided arguments
* @param type
* @param args
*/
createInstance<
ClassT extends new (...args: unknown[]) => unknown,
>(type: ClassT, ...args: ConstructorParameters<ClassT>): InstanceType<ClassT> {
// eslint-disable-next-line new-cap
return this.activateAndCall(() => new type(...args)) as InstanceType<ClassT>
}
/**
* Activates this injector and calls the function with provided arguments
* @param func function which should be called
* @param args args which should be passed to the called function
*/
callFunc<
FuncT extends (...args: unknown[]) => unknown
>(func: FuncT, ...args: Parameters<FuncT>): ReturnType<FuncT> {
return this.activateAndCall<ReturnType<FuncT>>(() => func(...args) as ReturnType<FuncT>)
}
/**
* Returns bound to the specified provider value. If the value is not found
* exception is thrown
* @param provider
*/
getValue<
ProviderT extends Provider<unknown>,
>(provider: ProviderT): ProviderValueType<ProviderT> {
const binder = this.getBinder(provider)
this.pushResolvingProvider(provider)
const value = this.activateAndCall(() => binder.getValue() as ProviderValueType<ProviderT>)
this.popResolvingProvder()
return value
}
/**
* Returns bound to the specified provider value. If the value is not found
* default value is returned
* @param provider
*/
tryGetValue<
ProviderT extends Provider<unknown>,
>(provider: ProviderT): ProviderValueType<ProviderT> | undefined
tryGetValue<
ProviderT extends Provider<unknown>,
DefValT,
>(provider: ProviderT, defVal: DefValT): ProviderValueType<ProviderT> | DefValT
tryGetValue (provider: Provider<unknown>, defValue?: unknown): unknown {
try {
return this.getValue(provider)
} catch (err) {
if (err instanceof NoBinderError) {
return defValue
}
throw err
}
}
private pushResolvingProvider (provider: Provider<unknown>): void {
this.checkCircularDependency(provider)
this.resolvingProviders.push(provider)
}
private popResolvingProvder (): void {
this.resolvingProviders.pop()
}
private getBinder<ValueT>(provider: Provider<ValueT>): Binder<ValueT> {
const binder = this.tryGetBinderRecursively(provider)
if (binder == null) {
throw new NoBinderError(provider)
}
return binder
}
/**
* Finds binder for the specified provider recursively up to the root injector
* @param provider
* @private
*/
private tryGetBinderRecursively<ValueT>(provider: Provider<ValueT>): Binder<ValueT> | undefined {
return (
this.binders.get(provider) ??
this.parent?.tryGetBinderRecursively(provider)
) as Binder<ValueT> | undefined
}
/**
* Checks is there circular dependency and throws error if so
* @param provider
* @private
*/
private checkCircularDependency (provider: Provider<unknown>): void {
const i = this.resolvingProviders.indexOf(provider)
if (i !== -1) {
const providers = [...this.resolvingProviders.slice(i), provider]
throw new CircularDependencyError(providers)
}
}
/**
* Temporary activates this injector calls provided function and returns its value
* @param func
* @private
*/
private activateAndCall<T>(func: () => T): T {
InjectorsStack.push(this)
const value = func()
InjectorsStack.pop()
return value
}
}