| 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 |
1x
1x
1x
1x
1x
1x
1x
22x
22x
22x
22x
4x
4x
4x
8x
8x
8x
8x
8x
4x
4x
9x
1x
8x
4x
4x
6x
6x
6x
6x
6x
6x
3x
6x
6x
6x
6x
6x
6x
6x
6x
6x
6x
14x
1x
13x
13x
13x
13x
13x
6x
6x
3x
6x
6x
48x
48x
48x
48x
48x
12x
24x
12x
12x
2x
2x
2x
2x
1x
1x
1x
5x
1x
4x
1x
3x
11x
11x
7x
4x
4x
4x
4x
2x
2x
2x
2x
1x
2x
6x
86x
1x
1x
1x
1x
1x
1x
8x
1x
1x
1x
1x
8x
8x
| import { DynamicModule, ForwardReference } from '@nestjs/common';
import {
EXCEPTION_FILTERS_METADATA,
GATEWAY_MIDDLEWARES,
GUARDS_METADATA,
INTERCEPTORS_METADATA,
METADATA,
PIPES_METADATA,
ROUTE_ARGS_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 { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util';
import {
isFunction,
isNil,
isUndefined,
} from '@nestjs/common/utils/shared.utils';
import { ApplicationConfig } from './application-config';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from './constants';
import { CircularDependencyException } from './errors/exceptions/circular-dependency.exception';
import { NestContainer } from './injector/container';
import { MetadataScanner } from './metadata-scanner';
interface ApplicationProviderWrapper {
moduleKey: string;
providerKey: string;
type: string;
}
export class DependenciesScanner {
private readonly applicationProvidersApplyMap: ApplicationProviderWrapper[] = [];
constructor(
private readonly container: NestContainer,
private readonly metadataScanner: MetadataScanner,
private readonly applicationConfig = new ApplicationConfig(),
) {}
public async scan(module: Type<any>) {
await this.scanForModules(module);
await this.scanModulesForDependencies();
this.container.bindGlobalScope();
}
public async scanForModules(
module: ForwardReference | Type<any> | DynamicModule,
scope: Type<any>[] = [],
ctxRegistry: (ForwardReference | DynamicModule | Type<any>)[] = [],
) {
await this.storeModule(module, scope);
ctxRegistry.push(module);
Iif (this.isForwardReference(module)) {
module = (module as ForwardReference).forwardRef();
}
const modules = !this.isDynamicModule(module as Type<any> | DynamicModule)
? this.reflectMetadata(module, METADATA.MODULES)
: [
...this.reflectMetadata(
(module as DynamicModule).module,
METADATA.MODULES,
),
...((module as DynamicModule).imports || []),
];
for (const innerModule of modules) {
Iif (ctxRegistry.includes(innerModule)) {
continue;
}
await this.scanForModules(
innerModule,
[].concat(scope, module),
ctxRegistry,
);
}
}
public async storeModule(module: any, scope: Type<any>[]) {
if (module && module.forwardRef) {
return this.container.addModule(module.forwardRef(), scope);
}
await this.container.addModule(module, scope);
}
public async scanModulesForDependencies() {
const modules = this.container.getModules();
for (const [token, { metatype }] of modules) {
await this.reflectRelatedModules(metatype, token, metatype.name);
this.reflectComponents(metatype, token);
this.reflectControllers(metatype, token);
this.reflectExports(metatype, token);
}
}
public async reflectRelatedModules(
module: Type<any>,
token: string,
context: string,
) {
const modules = [
...this.reflectMetadata(module, METADATA.MODULES),
...this.container.getDynamicMetadataByToken(
token,
METADATA.MODULES as 'modules',
),
...this.container.getDynamicMetadataByToken(
token,
METADATA.IMPORTS as 'imports',
),
];
for (const related of modules) {
await this.storeRelatedModule(related, token, context);
}
}
public reflectComponents(module: Type<any>, token: string) {
const components = [
...this.reflectMetadata(module, METADATA.COMPONENTS),
...this.container.getDynamicMetadataByToken(
token,
METADATA.COMPONENTS as 'components',
),
...this.container.getDynamicMetadataByToken(
token,
METADATA.PROVIDERS as 'providers',
),
];
components.forEach(component => {
this.storeComponent(component, token);
this.reflectComponentMetadata(component, token);
this.reflectDynamicMetadata(component, token);
});
}
public reflectComponentMetadata(component: Type<Injectable>, token: string) {
this.reflectGatewaysMiddleware(component, token);
}
public reflectControllers(module: Type<any>, token: string) {
const routes = [
...this.reflectMetadata(module, METADATA.CONTROLLERS),
...this.container.getDynamicMetadataByToken(
token,
METADATA.CONTROLLERS as 'controllers',
),
];
routes.forEach(route => {
this.storeRoute(route, token);
this.reflectDynamicMetadata(route, token);
});
}
public reflectDynamicMetadata(obj: Type<Injectable>, token: string) {
if (!obj || !obj.prototype) {
return;
}
this.reflectInjectables(obj, token, GUARDS_METADATA);
this.reflectInjectables(obj, token, INTERCEPTORS_METADATA);
this.reflectInjectables(obj, token, EXCEPTION_FILTERS_METADATA);
this.reflectInjectables(obj, token, PIPES_METADATA);
this.reflectParamInjectables(obj, token, ROUTE_ARGS_METADATA);
}
public reflectExports(module: Type<any>, token: string) {
const exports = [
...this.reflectMetadata(module, METADATA.EXPORTS),
...this.container.getDynamicMetadataByToken(
token,
METADATA.EXPORTS as 'exports',
),
];
exports.forEach(exportedComponent =>
this.storeExportedComponent(exportedComponent, token),
);
}
public reflectGatewaysMiddleware(component: Type<Injectable>, token: string) {
const middleware = this.reflectMetadata(component, GATEWAY_MIDDLEWARES);
middleware.forEach(ware => this.storeComponent(ware, token));
}
public reflectInjectables(
component: Type<Injectable>,
token: string,
metadataKey: string,
) {
const controllerInjectables = this.reflectMetadata(component, metadataKey);
const methodsInjectables = this.metadataScanner.scanFromPrototype(
null,
component.prototype,
this.reflectKeyMetadata.bind(this, component, metadataKey),
);
const flattenMethodsInjectables = methodsInjectables.reduce<any[]>(
(a: any[], b) => a.concat(b),
[],
);
const mergedInjectables = [
...controllerInjectables,
...flattenMethodsInjectables,
].filter(isFunction);
mergedInjectables.forEach(injectable =>
this.storeInjectable(injectable, token),
);
}
public reflectParamInjectables(
component: Type<Injectable>,
token: string,
metadataKey: string,
) {
const paramsMetadata = this.metadataScanner.scanFromPrototype(
null,
component.prototype,
method => Reflect.getMetadata(metadataKey, component, method),
);
const flatten = arr => arr.reduce((a, b) => a.concat(b), []);
const paramsInjectables = flatten(paramsMetadata).map(param =>
flatten(Object.keys(param).map(k => param[k].pipes)).filter(isFunction),
);
flatten(paramsInjectables).forEach(injectable =>
this.storeInjectable(injectable, token),
);
}
public reflectKeyMetadata(
component: Type<Injectable>,
key: string,
method: string,
) {
let prototype = component.prototype;
do {
const descriptor = Reflect.getOwnPropertyDescriptor(prototype, method);
if (!descriptor) {
continue;
}
return Reflect.getMetadata(key, descriptor.value);
} while (
// tslint:disable-next-line:no-conditional-assignment
(prototype = Reflect.getPrototypeOf(prototype)) &&
prototype !== Object.prototype &&
prototype
);
return undefined;
}
public async storeRelatedModule(
related: any,
token: string,
context: string,
) {
if (isUndefined(related)) {
throw new CircularDependencyException(context);
}
if (related && related.forwardRef) {
return this.container.addRelatedModule(related.forwardRef(), token);
}
await this.container.addRelatedModule(related, token);
}
public storeComponent(component, token: string) {
const isCustomProvider = component && !isNil(component.provide);
if (!isCustomProvider) {
return this.container.addComponent(component, token);
}
const applyProvidersMap = this.getApplyProvidersMap();
const providersKeys = Object.keys(applyProvidersMap);
const type = component.provide;
if (!providersKeys.includes(type)) {
return this.container.addComponent(component, token);
}
const providerToken = randomStringGenerator();
this.applicationProvidersApplyMap.push({
type,
moduleKey: token,
providerKey: providerToken,
});
this.container.addComponent(
{
...component,
provide: providerToken,
},
token,
);
}
public storeInjectable(component: Type<Injectable>, token: string) {
this.container.addInjectable(component, token);
}
public storeExportedComponent(
exportedComponent: Type<Injectable>,
token: string,
) {
this.container.addExportedComponent(exportedComponent, token);
}
public storeRoute(route: Type<Controller>, token: string) {
this.container.addController(route, token);
}
public reflectMetadata(metatype, metadataKey: string) {
return Reflect.getMetadata(metadataKey, metatype) || [];
}
public applyApplicationProviders() {
const applyProvidersMap = this.getApplyProvidersMap();
this.applicationProvidersApplyMap.forEach(
({ moduleKey, providerKey, type }) => {
const modules = this.container.getModules();
const { components } = modules.get(moduleKey);
const { instance } = components.get(providerKey);
applyProvidersMap[type](instance);
},
);
}
public getApplyProvidersMap(): { [type: string]: Function } {
return {
[APP_INTERCEPTOR]: interceptor =>
this.applicationConfig.addGlobalInterceptor(interceptor),
[APP_PIPE]: pipe => this.applicationConfig.addGlobalPipe(pipe),
[APP_GUARD]: guard => this.applicationConfig.addGlobalGuard(guard),
[APP_FILTER]: filter => this.applicationConfig.addGlobalFilter(filter),
};
}
public isDynamicModule(
module: Type<any> | DynamicModule,
): module is DynamicModule {
return module && !!(module as DynamicModule).module;
}
public isForwardReference(
module: Type<any> | DynamicModule | ForwardReference,
): module is ForwardReference {
return module && !!(module as ForwardReference).forwardRef;
}
}
|