-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
router-explorer.ts
434 lines (405 loc) 路 13.3 KB
/
router-explorer.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
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
import { HttpServer } from '@nestjs/common';
import {
METHOD_METADATA,
PATH_METADATA,
VERSION_METADATA,
} from '@nestjs/common/constants';
import { RequestMethod, VersioningType } from '@nestjs/common/enums';
import { InternalServerErrorException } from '@nestjs/common/exceptions';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { VersionValue } from '@nestjs/common/interfaces/version-options.interface';
import { Logger } from '@nestjs/common/services/logger.service';
import {
addLeadingSlash,
isString,
isUndefined,
} from '@nestjs/common/utils/shared.utils';
import * as pathToRegexp from 'path-to-regexp';
import { ApplicationConfig } from '../application-config';
import { UnknownRequestMappingException } from '../errors/exceptions/unknown-request-mapping.exception';
import { GuardsConsumer } from '../guards/guards-consumer';
import { GuardsContextCreator } from '../guards/guards-context-creator';
import { ContextIdFactory } from '../helpers/context-id-factory';
import { ExecutionContextHost } from '../helpers/execution-context-host';
import {
ROUTE_MAPPED_MESSAGE,
VERSIONED_ROUTE_MAPPED_MESSAGE,
} from '../helpers/messages';
import { RouterMethodFactory } from '../helpers/router-method-factory';
import { STATIC_CONTEXT } from '../injector/constants';
import { NestContainer } from '../injector/container';
import { Injector } from '../injector/injector';
import { ContextId, InstanceWrapper } from '../injector/instance-wrapper';
import { Module } from '../injector/module';
import { InterceptorsConsumer } from '../interceptors/interceptors-consumer';
import { InterceptorsContextCreator } from '../interceptors/interceptors-context-creator';
import { MetadataScanner } from '../metadata-scanner';
import { PipesConsumer } from '../pipes/pipes-consumer';
import { PipesContextCreator } from '../pipes/pipes-context-creator';
import { ExceptionsFilter } from './interfaces/exceptions-filter.interface';
import { RoutePathMetadata } from './interfaces/route-path-metadata.interface';
import { REQUEST_CONTEXT_ID } from './request/request-constants';
import { RouteParamsFactory } from './route-params-factory';
import { RoutePathFactory } from './route-path-factory';
import { RouterExecutionContext } from './router-execution-context';
import { RouterProxy, RouterProxyCallback } from './router-proxy';
export interface RouteDefinition {
path: string[];
requestMethod: RequestMethod;
targetCallback: RouterProxyCallback;
methodName: string;
version?: VersionValue;
}
export class RouterExplorer {
private readonly executionContextCreator: RouterExecutionContext;
private readonly routerMethodFactory = new RouterMethodFactory();
private readonly logger = new Logger(RouterExplorer.name, {
timestamp: true,
});
private readonly exceptionFiltersCache = new WeakMap();
constructor(
private readonly metadataScanner: MetadataScanner,
private readonly container: NestContainer,
private readonly injector?: Injector,
private readonly routerProxy?: RouterProxy,
private readonly exceptionsFilter?: ExceptionsFilter,
private readonly config?: ApplicationConfig,
private readonly routePathFactory?: RoutePathFactory,
) {
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,
applicationRef: T,
host: string | RegExp | Array<string | RegExp>,
routePathMetadata: RoutePathMetadata,
) {
const { instance } = instanceWrapper;
const routerPaths = this.scanForPaths(instance);
this.applyPathsToRouterProxy(
applicationRef,
routerPaths,
instanceWrapper,
moduleKey,
routePathMetadata,
host,
);
}
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 scanForPaths(
instance: Controller,
prototype?: object,
): RouteDefinition[] {
const instancePrototype = isUndefined(prototype)
? Object.getPrototypeOf(instance)
: prototype;
return this.metadataScanner.scanFromPrototype<Controller, RouteDefinition>(
instance,
instancePrototype,
method => this.exploreMethodMetadata(instance, instancePrototype, method),
);
}
public exploreMethodMetadata(
instance: Controller,
prototype: object,
methodName: string,
): RouteDefinition {
const instanceCallback = instance[methodName];
const prototypeCallback = prototype[methodName];
const routePath = Reflect.getMetadata(PATH_METADATA, prototypeCallback);
if (isUndefined(routePath)) {
return null;
}
const requestMethod: RequestMethod = Reflect.getMetadata(
METHOD_METADATA,
prototypeCallback,
);
const version: VersionValue | undefined = Reflect.getMetadata(
VERSION_METADATA,
prototypeCallback,
);
const path = isString(routePath)
? [addLeadingSlash(routePath)]
: routePath.map((p: string) => addLeadingSlash(p));
return {
path,
requestMethod,
targetCallback: instanceCallback,
methodName,
version,
};
}
public applyPathsToRouterProxy<T extends HttpServer>(
router: T,
routeDefinitions: RouteDefinition[],
instanceWrapper: InstanceWrapper,
moduleKey: string,
routePathMetadata: RoutePathMetadata,
host: string | RegExp | Array<string | RegExp>,
) {
(routeDefinitions || []).forEach(routeDefinition => {
const { version: methodVersion } = routeDefinition;
routePathMetadata.methodVersion = methodVersion;
this.applyCallbackToRouter(
router,
routeDefinition,
instanceWrapper,
moduleKey,
routePathMetadata,
host,
);
});
}
private applyCallbackToRouter<T extends HttpServer>(
router: T,
routeDefinition: RouteDefinition,
instanceWrapper: InstanceWrapper,
moduleKey: string,
routePathMetadata: RoutePathMetadata,
host: string | RegExp | Array<string | RegExp>,
) {
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 => routerMethodRef(path, routeHandler));
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));
}
});
});
}
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) => {
const keys = [];
const regexp = pathToRegexp(host, keys);
return { regexp, 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) {
exp.keys.forEach((key, i) => (req.hosts[key.name] = match[i + 1]));
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;
return async <TRequest extends Record<any, any>, TResponse>(
req: TRequest,
res: TResponse,
next: () => void,
) => {
try {
const contextId = this.getContextId(req);
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,
): 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,
});
this.container.registerRequestProvider(
contextId.getParent ? contextId.payload : request,
contextId,
);
}
return contextId;
}
}