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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425 | 1x
1x
1x
1x
1x
1x
2x
2x
2x
1x
1x
1x
1x
1x
1x
7x
1x
6x
6x
2x
4x
4x
4x
8x
8x
8x
8x
9x
1x
8x
8x
8x
8x
1x
7x
1x
6x
6x
6x
6x
6x
6x
6x
6x
6x
6x
4x
4x
4x
4x
4x
6x
6x
6x
6x
6x
6x
6x
7x
1x
6x
6x
10x
8x
2x
2x
10x
10x
10x
5x
10x
1x
10x
10x
10x
3x
10x
3x
3x
1x
2x
7x
7x
7x
7x
4x
4x
4x
4x
2x
2x
2x
2x
2x
1x
1x
7x
6x
6x
6x
2x
2x
2x
2x
2x
6x
6x
6x
6x
8x
1x
7x
5x
4x
6x
6x
6x
6x
6x
| import {
OPTIONAL_DEPS_METADATA,
OPTIONAL_PROPERTY_DEPS_METADATA,
PARAMTYPES_METADATA,
PROPERTY_DEPS_METADATA,
SELF_DECLARED_DEPS_METADATA,
} from '@nestjs/common/constants';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { Injectable } from '@nestjs/common/interfaces/injectable.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
import {
isFunction,
isNil,
isObject,
isUndefined,
} from '@nestjs/common/utils/shared.utils';
import { RuntimeException } from '../errors/exceptions/runtime.exception';
import { UndefinedDependencyException } from '../errors/exceptions/undefined-dependency.exception';
import { UnknownDependenciesException } from '../errors/exceptions/unknown-dependencies.exception';
import { MiddlewareWrapper } from '../middleware/container';
import { InstanceWrapper } from './container';
import { Module } from './module';
/**
* The type of an injectable dependency
*/
export type InjectorDependency = Type<any> | Function | string;
/**
* The property-based dependency
*/
export interface PropertyDependency {
key: string;
name: InjectorDependency;
isOptional?: boolean;
instance?: any;
}
/**
* Context of a dependency which gets injected by
* the injector
*/
export interface InjectorDependencyContext {
/**
* The name of the property key (property-based injection)
*/
key?: string;
/**
* The name of the function or injection token
*/
name?: string;
/**
* The index of the dependency which gets injected
* from the dependencies array
*/
index?: number;
/**
* The dependency array which gets injected
*/
dependencies?: InjectorDependency[];
}
export class Injector {
public async loadInstanceOfMiddleware(
wrapper: MiddlewareWrapper,
collection: Map<string, MiddlewareWrapper>,
module: Module,
) {
const { metatype } = wrapper;
const currentMetatype = collection.get(metatype.name);
if (currentMetatype.instance !== null) {
return;
}
await this.resolveConstructorParams(
wrapper as any,
module,
null,
instances => {
collection.set(metatype.name, {
instance: new metatype(...instances),
metatype,
});
},
);
}
public async loadInstanceOfRoute(
wrapper: InstanceWrapper<Controller>,
module: Module,
) {
const routes = module.routes;
await this.loadInstance<Controller>(wrapper, routes, module);
}
public async loadInstanceOfInjectable(
wrapper: InstanceWrapper<Controller>,
module: Module,
) {
const injectables = module.injectables;
await this.loadInstance<Controller>(wrapper, injectables, module);
}
public loadPrototypeOfInstance<T>(
{ metatype, name }: InstanceWrapper<T>,
collection: Map<string, InstanceWrapper<T>>,
) {
if (!collection) {
return null;
}
const target = collection.get(name);
if (target.isResolved || !isNil(target.inject) || !metatype.prototype) {
return null;
}
collection.set(name, {
...collection.get(name),
instance: Object.create(metatype.prototype),
});
}
public async loadInstanceOfComponent(
wrapper: InstanceWrapper<Injectable>,
module: Module,
) {
const components = module.components;
await this.loadInstance<Injectable>(wrapper, components, module);
}
public applyDoneHook<T>(wrapper: InstanceWrapper<T>): () => void {
let done: () => void;
wrapper.done$ = new Promise<void>((resolve, reject) => {
done = resolve;
});
wrapper.isPending = true;
return done;
}
public async loadInstance<T>(
wrapper: InstanceWrapper<T>,
collection: Map<string, InstanceWrapper<any>>,
module: Module,
) {
if (wrapper.isPending) {
return wrapper.done$;
}
const done = this.applyDoneHook(wrapper);
const { name, inject } = wrapper;
const targetWrapper = collection.get(name);
if (isUndefined(targetWrapper)) {
throw new RuntimeException();
}
if (targetWrapper.isResolved) {
return;
}
const callback = async instances => {
const properties = await this.resolveProperties(wrapper, module, inject);
const instance = await this.instantiateClass(
instances,
wrapper,
targetWrapper,
);
this.applyProperties(instance, properties);
done();
};
await this.resolveConstructorParams<T>(wrapper, module, inject, callback);
}
public async resolveConstructorParams<T>(
wrapper: InstanceWrapper<T>,
module: Module,
inject: InjectorDependency[],
callback: (args) => void,
) {
const dependencies = isNil(inject)
? this.reflectConstructorParams(wrapper.metatype)
: inject;
const optionalDependenciesIds = isNil(inject)
? this.reflectOptionalParams(wrapper.metatype)
: [];
let isResolved = true;
const instances = await Promise.all(
dependencies.map(async (param, index) => {
try {
const paramWrapper = await this.resolveSingleParam<T>(
wrapper,
param,
{ index, dependencies },
module,
);
Iif (!paramWrapper.isResolved && !paramWrapper.forwardRef) {
isResolved = false;
}
return paramWrapper.instance;
} catch (err) {
const isOptional = optionalDependenciesIds.includes(index);
if (!isOptional) {
throw err;
}
return undefined;
}
}),
);
isResolved && (await callback(instances));
}
public reflectConstructorParams<T>(type: Type<T>): any[] {
const paramtypes = Reflect.getMetadata(PARAMTYPES_METADATA, type) || [];
const selfParams = this.reflectSelfParams<T>(type);
selfParams.forEach(({ index, param }) => (paramtypes[index] = param));
return paramtypes;
}
public reflectOptionalParams<T>(type: Type<T>): any[] {
return Reflect.getMetadata(OPTIONAL_DEPS_METADATA, type) || [];
}
public reflectSelfParams<T>(type: Type<T>): any[] {
return Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, type) || [];
}
public async resolveSingleParam<T>(
wrapper: InstanceWrapper<T>,
param: Type<any> | string | symbol | any,
dependencyContext: InjectorDependencyContext,
module: Module,
) {
if (isUndefined(param)) {
throw new UndefinedDependencyException(
wrapper.name,
dependencyContext,
module,
);
}
const token = this.resolveParamToken(wrapper, param);
return this.resolveComponentInstance<T>(
module,
isFunction(token) ? (token as Type<any>).name : token,
dependencyContext,
wrapper,
);
}
public resolveParamToken<T>(
wrapper: InstanceWrapper<T>,
param: Type<any> | string | symbol | any,
) {
if (!param.forwardRef) {
return param;
}
wrapper.forwardRef = true;
return param.forwardRef();
}
public async resolveComponentInstance<T>(
module: Module,
name: any,
dependencyContext: InjectorDependencyContext,
wrapper: InstanceWrapper<T>,
) {
const components = module.components;
const instanceWrapper = await this.lookupComponent(
components,
module,
{ ...dependencyContext, name },
wrapper,
);
if (!instanceWrapper.isResolved && !instanceWrapper.forwardRef) {
await this.loadInstanceOfComponent(instanceWrapper, module);
}
if (instanceWrapper.async) {
instanceWrapper.instance = await instanceWrapper.instance;
}
return instanceWrapper;
}
public async lookupComponent<T = any>(
components: Map<string, any>,
module: Module,
dependencyContext: InjectorDependencyContext,
wrapper: InstanceWrapper<T>,
) {
const { name } = dependencyContext;
const scanInExports = () =>
this.lookupComponentInExports(dependencyContext, module, wrapper);
return components.has(name) ? components.get(name) : scanInExports();
}
public async lookupComponentInExports<T = any>(
dependencyContext: InjectorDependencyContext,
module: Module,
wrapper: InstanceWrapper<T>,
) {
const instanceWrapper = await this.lookupComponentInRelatedModules(
module,
dependencyContext.name,
);
if (isNil(instanceWrapper)) {
throw new UnknownDependenciesException(
wrapper.name,
dependencyContext,
module,
);
}
return instanceWrapper;
}
public async lookupComponentInRelatedModules(
module: Module,
name: any,
moduleRegistry = [],
) {
let componentRef = null;
const relatedModules: Set<Module> = module.relatedModules || new Set();
const children = [...relatedModules.values()].filter(item => item);
for (const relatedModule of children) {
Iif (moduleRegistry.includes(relatedModule.id)) {
continue;
}
moduleRegistry.push(relatedModule.id);
const { components, exports } = relatedModule;
if (!exports.has(name) || !components.has(name)) {
const instanceRef = await this.lookupComponentInRelatedModules(
relatedModule,
name,
moduleRegistry,
);
Iif (instanceRef) {
return instanceRef;
}
continue;
}
componentRef = components.get(name);
if (!componentRef.isResolved && !componentRef.forwardRef) {
await this.loadInstanceOfComponent(componentRef, relatedModule);
break;
}
}
return componentRef;
}
public async resolveProperties<T>(
wrapper: InstanceWrapper<T>,
module: Module,
inject?: InjectorDependency[],
): Promise<PropertyDependency[]> {
Iif (!isNil(inject)) {
return [];
}
const properties = this.reflectProperties(wrapper.metatype);
const instances = await Promise.all(
properties.map(async (item: PropertyDependency) => {
try {
const dependencyContext = {
key: item.key,
name: item.name as string,
};
const paramWrapper = await this.resolveSingleParam<T>(
wrapper,
item.name,
dependencyContext,
module,
);
return (paramWrapper && paramWrapper.instance) || undefined;
} catch (err) {
if (!item.isOptional) {
throw err;
}
return undefined;
}
}),
);
return properties.map((item: PropertyDependency, index: number) => ({
...item,
instance: instances[index],
}));
}
public reflectProperties<T>(type: Type<T>): PropertyDependency[] {
const properties = Reflect.getMetadata(PROPERTY_DEPS_METADATA, type) || [];
const optionalKeys: string[] =
Reflect.getMetadata(OPTIONAL_PROPERTY_DEPS_METADATA, type) || [];
return properties.map(item => ({
...item,
name: item.type,
isOptional: optionalKeys.includes(item.key),
}));
}
public applyProperties<T = any>(
instance: T,
properties: PropertyDependency[],
) {
if (!isObject(instance)) {
return undefined;
}
properties
.filter(item => !isNil(item.instance))
.forEach(item => (instance[item.key] = item.instance));
}
public async instantiateClass<T = any>(
instances: any[],
wrapper: InstanceWrapper<any>,
targetMetatype: InstanceWrapper<any>,
): Promise<T> {
const { metatype, inject } = wrapper;
Eif (isNil(inject)) {
targetMetatype.instance = wrapper.forwardRef
? Object.assign(targetMetatype.instance, new metatype(...instances))
: new metatype(...instances);
} else {
const factoryResult = ((targetMetatype.metatype as any) as Function)(
...instances,
);
targetMetatype.instance = await factoryResult;
}
targetMetatype.isResolved = true;
return targetMetatype.instance;
}
}
|