-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathrouter-explorer.ts
More file actions
522 lines (485 loc) 路 16.4 KB
/
Copy pathrouter-explorer.ts
File metadata and controls
522 lines (485 loc) 路 16.4 KB
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import type { HttpServer } from '@nestjs/common';
import { pathToRegexp } from 'path-to-regexp';
import { ApplicationConfig } from '../application-config.js';
import { UnknownRequestMappingException } from '../errors/exceptions/unknown-request-mapping.exception.js';
import { GuardsConsumer, GuardsContextCreator } from '../guards/index.js';
import { ContextIdFactory } from '../helpers/context-id-factory.js';
import { ExecutionContextHost } from '../helpers/execution-context-host.js';
import {
ROUTE_MAPPED_MESSAGE,
VERSIONED_ROUTE_MAPPED_MESSAGE,
} from '../helpers/messages.js';
import { RouterMethodFactory } from '../helpers/router-method-factory.js';
import { STATIC_CONTEXT } from '../injector/constants.js';
import { NestContainer } from '../injector/container.js';
import { Injector } from '../injector/injector.js';
import { ContextId, InstanceWrapper } from '../injector/instance-wrapper.js';
import { Module } from '../injector/module.js';
import { GraphInspector } from '../inspector/graph-inspector.js';
import {
Entrypoint,
HttpEntrypointMetadata,
} from '../inspector/interfaces/entrypoint.interface.js';
import {
InterceptorsConsumer,
InterceptorsContextCreator,
} from '../interceptors/index.js';
import { MetadataScanner } from '../metadata-scanner.js';
import { PipesConsumer, PipesContextCreator } from '../pipes/index.js';
import { ExceptionsFilter } from './interfaces/exceptions-filter.interface.js';
import { ResolvedRoute } from './interfaces/resolved-route.interface.js';
import { RoutePathMetadata } from './interfaces/route-path-metadata.interface.js';
import { RouteResolutionOptions } from './interfaces/route-resolution-options.interface.js';
import { PathsExplorer } from './paths-explorer.js';
import { REQUEST_CONTEXT_ID } from './request/request-constants.js';
import { RouteParamsFactory } from './route-params-factory.js';
import { RoutePathFactory } from './route-path-factory.js';
import { RouterExecutionContext } from './router-execution-context.js';
import { RouterProxy, RouterProxyCallback } from './router-proxy.js';
import {
PATH_METADATA,
type Controller,
type VersionValue,
addLeadingSlash,
isUndefined,
} from '@nestjs/common/internal';
import {
RequestMethod,
VersioningType,
InternalServerErrorException,
type Type,
Logger,
} from '@nestjs/common';
export interface RouteDefinition {
path: string[];
requestMethod: RequestMethod;
targetCallback: RouterProxyCallback;
methodName: string;
version?: VersionValue;
}
export class RouterExplorer {
private readonly executionContextCreator: RouterExecutionContext;
private readonly pathsExplorer: PathsExplorer;
private readonly routerMethodFactory = new RouterMethodFactory();
private readonly logger = new Logger(RouterExplorer.name, {
timestamp: true,
});
private readonly exceptionFiltersCache = new WeakMap();
constructor(
metadataScanner: MetadataScanner,
private readonly container: NestContainer,
private readonly injector: Injector,
private readonly routerProxy: RouterProxy,
private readonly exceptionsFilter: ExceptionsFilter,
config: ApplicationConfig,
private readonly routePathFactory: RoutePathFactory,
private readonly graphInspector: GraphInspector,
) {
this.pathsExplorer = new PathsExplorer(metadataScanner);
const routeParamsFactory = new RouteParamsFactory();
const pipesContextCreator = new PipesContextCreator(container, config);
const pipesConsumer = new PipesConsumer();
const guardsContextCreator = new GuardsContextCreator(container, config);
const guardsConsumer = new GuardsConsumer();
const interceptorsContextCreator = new InterceptorsContextCreator(
container,
config,
);
const interceptorsConsumer = new InterceptorsConsumer();
this.executionContextCreator = new RouterExecutionContext(
routeParamsFactory,
pipesContextCreator,
pipesConsumer,
guardsContextCreator,
guardsConsumer,
interceptorsContextCreator,
interceptorsConsumer,
container.getHttpAdapterRef(),
);
}
public explore<T extends HttpServer = any>(
instanceWrapper: InstanceWrapper,
moduleKey: string,
httpAdapterRef: T,
host: string | RegExp | Array<string | RegExp>,
routePathMetadata: RoutePathMetadata,
options: RouteResolutionOptions = {},
) {
const { instance } = instanceWrapper;
const routerPaths = this.pathsExplorer.scanForPaths(instance);
this.applyPathsToRouterProxy(
httpAdapterRef,
routerPaths,
instanceWrapper,
moduleKey,
routePathMetadata,
host,
options,
);
}
public extractRouterPath(metatype: Type<Controller>): string[] {
const path = Reflect.getMetadata(PATH_METADATA, metatype);
if (isUndefined(path)) {
throw new UnknownRequestMappingException(metatype);
}
if (Array.isArray(path)) {
return path.map(p => addLeadingSlash(p));
}
return [addLeadingSlash(path)];
}
public applyPathsToRouterProxy<T extends HttpServer>(
router: T,
routeDefinitions: RouteDefinition[],
instanceWrapper: InstanceWrapper,
moduleKey: string,
routePathMetadata: RoutePathMetadata,
host: string | RegExp | Array<string | RegExp>,
options: RouteResolutionOptions = {},
) {
(routeDefinitions || []).forEach(routeDefinition => {
const { version: methodVersion } = routeDefinition;
routePathMetadata.methodVersion = methodVersion;
this.applyCallbackToRouter(
router,
routeDefinition,
instanceWrapper,
moduleKey,
routePathMetadata,
host,
options,
);
});
}
private applyCallbackToRouter<T extends HttpServer>(
router: T,
routeDefinition: RouteDefinition,
instanceWrapper: InstanceWrapper,
moduleKey: string,
routePathMetadata: RoutePathMetadata,
host: string | RegExp | Array<string | RegExp>,
options: RouteResolutionOptions = {},
) {
const { onRouteResolved, deferRegistration = false } = options;
const {
path: paths,
requestMethod,
targetCallback,
methodName,
} = routeDefinition;
const { instance } = instanceWrapper;
const routerMethodRef = this.routerMethodFactory
.get(router, requestMethod)
.bind(router);
const isRequestScoped = !instanceWrapper.isDependencyTreeStatic();
const proxy = isRequestScoped
? this.createRequestScopedHandler(
instanceWrapper,
requestMethod,
this.container.getModuleByKey(moduleKey)!,
moduleKey,
methodName,
)
: this.createCallbackProxy(
instance,
targetCallback,
methodName,
moduleKey,
requestMethod,
);
const isVersioned =
(routePathMetadata.methodVersion ||
routePathMetadata.controllerVersion) &&
routePathMetadata.versioningOptions;
let routeHandler = this.applyHostFilter(host, proxy);
paths.forEach(path => {
if (
isVersioned &&
routePathMetadata.versioningOptions!.type !== VersioningType.URI
) {
// All versioning (except for URI Versioning) is done via the "Version Filter"
routeHandler = this.applyVersionFilter(
router,
routePathMetadata,
routeHandler,
);
}
routePathMetadata.methodPath = path;
const pathsToRegister = this.routePathFactory.create(
routePathMetadata,
requestMethod,
);
pathsToRegister.forEach(path => {
const normalizedPath = router.normalizePath
? router.normalizePath(path)
: path;
const entrypointDefinition: Entrypoint<HttpEntrypointMetadata> = {
type: 'http-endpoint',
methodName,
className: instanceWrapper.name,
classNodeId: instanceWrapper.id,
metadata: {
key: path,
path,
requestMethod: RequestMethod[
requestMethod
] as keyof typeof RequestMethod,
methodVersion: routePathMetadata.methodVersion,
controllerVersion: routePathMetadata.controllerVersion,
},
};
if (!deferRegistration) {
this.copyMetadataToCallback(targetCallback, routeHandler);
const httpAdapter = this.container.getHttpAdapterRef();
const onRouteTriggered = httpAdapter.getOnRouteTriggered?.();
if (onRouteTriggered) {
routerMethodRef(normalizedPath, (...args: unknown[]) => {
onRouteTriggered(requestMethod, path);
return routeHandler(...args);
});
} else {
routerMethodRef(normalizedPath, routeHandler);
}
}
onRouteResolved?.({
method: requestMethod,
path: normalizedPath,
rawPath: path,
host,
version:
routePathMetadata.methodVersion ??
routePathMetadata.controllerVersion,
methodVersion: routePathMetadata.methodVersion,
controllerVersion: routePathMetadata.controllerVersion,
handler: routeHandler as unknown as (...args: unknown[]) => unknown,
targetCallback,
methodName,
instanceWrapper,
});
this.graphInspector.insertEntrypointDefinition<HttpEntrypointMetadata>(
entrypointDefinition,
instanceWrapper.id,
);
});
const pathsToLog = this.routePathFactory.create(
{
...routePathMetadata,
versioningOptions: undefined,
},
requestMethod,
);
pathsToLog.forEach(path => {
if (isVersioned) {
const version = this.routePathFactory.getVersion(routePathMetadata);
this.logger.log(
VERSIONED_ROUTE_MAPPED_MESSAGE(path, requestMethod, version!),
);
} else {
this.logger.log(ROUTE_MAPPED_MESSAGE(path, requestMethod));
}
});
});
}
/**
* Registers a previously resolved route on the underlying HTTP adapter.
* Used when route registration has been deferred (e.g. when sorting
* routes by specificity) so the caller can choose the order in which
* routes are installed on the adapter.
*/
public registerResolvedRoute<T extends HttpServer>(
router: T,
route: ResolvedRoute,
): void {
const routerMethodRef = this.routerMethodFactory
.get(router, route.method)
.bind(router);
this.copyMetadataToCallback(route.targetCallback, route.handler);
const normalizedPath = route.path;
const rawPath = route.rawPath ?? route.path;
const httpAdapter = this.container.getHttpAdapterRef();
const onRouteTriggered = httpAdapter.getOnRouteTriggered?.();
if (onRouteTriggered) {
routerMethodRef(normalizedPath, (...args: unknown[]) => {
onRouteTriggered(route.method, rawPath);
return route.handler(...args);
});
} else {
routerMethodRef(normalizedPath, route.handler);
}
}
private applyHostFilter(
host: string | RegExp | Array<string | RegExp>,
handler: Function,
) {
if (!host) {
return handler;
}
const httpAdapterRef = this.container.getHttpAdapterRef();
const hosts = Array.isArray(host) ? host : [host];
const hostRegExps = hosts.map((host: string | RegExp) => {
if (typeof host === 'string') {
try {
return pathToRegexp(host);
} catch (e) {
if (e instanceof TypeError) {
this.logger.error(
`Unsupported host "${host}" syntax. In past releases, ?, *, and + were used to denote optional or repeating path parameters. The latest version of "path-to-regexp" now requires the use of named parameters. For example, instead of using a route like /users/* to capture all routes starting with "/users", you should use /users/*path. Please see the migration guide for more information.`,
);
}
throw e;
}
}
return { regexp: host, keys: [] };
});
const unsupportedFilteringErrorMessage = Array.isArray(host)
? `HTTP adapter does not support filtering on hosts: ["${host.join(
'", "',
)}"]`
: `HTTP adapter does not support filtering on host: "${host}"`;
return <TRequest extends Record<string, any> = any, TResponse = any>(
req: TRequest,
res: TResponse,
next: () => void,
) => {
(req as Record<string, any>).hosts = {};
const hostname = httpAdapterRef.getRequestHostname(req) || '';
for (const exp of hostRegExps) {
const match = hostname.match(exp.regexp);
if (match) {
if (exp.keys.length > 0) {
exp.keys.forEach((key, i) => (req.hosts[key.name] = match[i + 1]));
} else if (exp.regexp && match.groups) {
for (const groupName in match.groups) {
req.hosts[groupName] = match.groups[groupName];
}
}
return handler(req, res, next);
}
}
if (!next) {
throw new InternalServerErrorException(
unsupportedFilteringErrorMessage,
);
}
return next();
};
}
private applyVersionFilter<T extends HttpServer>(
router: T,
routePathMetadata: RoutePathMetadata,
handler: Function,
) {
const version = this.routePathFactory.getVersion(routePathMetadata)!;
return router.applyVersionFilter(
handler,
version,
routePathMetadata.versioningOptions!,
);
}
private createCallbackProxy(
instance: Controller,
callback: RouterProxyCallback,
methodName: string,
moduleRef: string,
requestMethod: RequestMethod,
contextId = STATIC_CONTEXT,
inquirerId?: string,
) {
const executionContext = this.executionContextCreator.create(
instance,
callback,
methodName,
moduleRef,
requestMethod,
contextId,
inquirerId,
);
const exceptionFilter = this.exceptionsFilter.create(
instance,
callback,
moduleRef,
contextId,
inquirerId,
);
return this.routerProxy.createProxy(executionContext, exceptionFilter);
}
public createRequestScopedHandler(
instanceWrapper: InstanceWrapper,
requestMethod: RequestMethod,
moduleRef: Module,
moduleKey: string,
methodName: string,
) {
const { instance } = instanceWrapper;
const collection = moduleRef.controllers;
const isTreeDurable = instanceWrapper.isDependencyTreeDurable();
return async <TRequest extends Record<any, any>, TResponse>(
req: TRequest,
res: TResponse,
next: () => void,
) => {
try {
const contextId = this.getContextId(req, isTreeDurable);
const contextInstance = await this.injector.loadPerContext(
instance,
moduleRef,
collection,
contextId,
);
await this.createCallbackProxy(
contextInstance,
contextInstance[methodName],
methodName,
moduleKey,
requestMethod,
contextId,
instanceWrapper.id,
)(req, res, next);
} catch (err) {
let exceptionFilter = this.exceptionFiltersCache.get(
instance[methodName],
);
if (!exceptionFilter) {
exceptionFilter = this.exceptionsFilter.create(
instance,
instance[methodName],
moduleKey,
);
this.exceptionFiltersCache.set(instance[methodName], exceptionFilter);
}
const host = new ExecutionContextHost([req, res, next]);
exceptionFilter.next(err, host);
}
};
}
private getContextId<T extends Record<any, unknown> = any>(
request: T,
isTreeDurable: boolean,
): ContextId {
const contextId = ContextIdFactory.getByRequest(request);
if (!request[REQUEST_CONTEXT_ID as any]) {
Object.defineProperty(request, REQUEST_CONTEXT_ID, {
value: contextId,
enumerable: false,
writable: false,
configurable: false,
});
const requestProviderValue = isTreeDurable
? contextId.payload
: Object.assign(request, contextId.payload);
this.container.registerRequestProvider(requestProviderValue, contextId);
}
return contextId;
}
private copyMetadataToCallback(
originalCallback: RouterProxyCallback,
targetCallback: Function,
) {
for (const key of Reflect.getMetadataKeys(originalCallback)) {
Reflect.defineMetadata(
key,
Reflect.getMetadata(key, originalCallback),
targetCallback,
);
}
}
}