-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
router-explorer.ts
305 lines (286 loc) · 9.29 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
import { HttpServer } from '@nestjs/common';
import { METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { RequestMethod } from '@nestjs/common/enums/request-method.enum';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { Logger } from '@nestjs/common/services/logger.service';
import {
isString,
isUndefined,
validatePath,
} from '@nestjs/common/utils/shared.utils';
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 { createContextId } from '../helpers/context-id-factory';
import { ExecutionContextHost } from '../helpers/execution-context-host';
import { 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 { REQUEST } from './request';
import { REQUEST_CONTEXT_ID } from './request/request-constants';
import { RouteParamsFactory } from './route-params-factory';
import { RouterExecutionContext } from './router-execution-context';
import { RouterProxy, RouterProxyCallback } from './router-proxy';
export interface RoutePathProperties {
path: string[];
requestMethod: RequestMethod;
targetCallback: RouterProxyCallback;
methodName: string;
}
export class RouterExplorer {
private readonly executionContextCreator: RouterExecutionContext;
private readonly routerMethodFactory = new RouterMethodFactory();
private readonly logger = new Logger(RouterExplorer.name, 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,
config?: ApplicationConfig,
) {
this.executionContextCreator = new RouterExecutionContext(
new RouteParamsFactory(),
new PipesContextCreator(container, config),
new PipesConsumer(),
new GuardsContextCreator(container, config),
new GuardsConsumer(),
new InterceptorsContextCreator(container, config),
new InterceptorsConsumer(),
container.getHttpAdapterRef(),
);
}
public explore<T extends HttpServer = any>(
instanceWrapper: InstanceWrapper,
module: string,
applicationRef: T,
basePath: string,
) {
const { instance } = instanceWrapper;
const routerPaths = this.scanForPaths(instance);
this.applyPathsToRouterProxy(
applicationRef,
routerPaths,
instanceWrapper,
module,
basePath,
);
}
public extractRouterPath(
metatype: Type<Controller>,
prefix?: string,
): string {
let path = Reflect.getMetadata(PATH_METADATA, metatype);
if (prefix) path = prefix + this.validateRoutePath(path);
return this.validateRoutePath(path);
}
public validateRoutePath(path: string): string {
if (isUndefined(path)) {
throw new UnknownRequestMappingException();
}
return validatePath(path);
}
public scanForPaths(
instance: Controller,
prototype?: any,
): RoutePathProperties[] {
const instancePrototype = isUndefined(prototype)
? Object.getPrototypeOf(instance)
: prototype;
return this.metadataScanner.scanFromPrototype<
Controller,
RoutePathProperties
>(instance, instancePrototype, method =>
this.exploreMethodMetadata(instance, instancePrototype, method),
);
}
public exploreMethodMetadata(
instance: Controller,
instancePrototype: any,
methodName: string,
): RoutePathProperties {
const targetCallback = instancePrototype[methodName];
const routePath = Reflect.getMetadata(PATH_METADATA, targetCallback);
if (isUndefined(routePath)) {
return null;
}
const requestMethod: RequestMethod = Reflect.getMetadata(
METHOD_METADATA,
targetCallback,
);
const path = isString(routePath)
? [this.validateRoutePath(routePath)]
: routePath.map(p => this.validateRoutePath(p));
return {
path,
requestMethod,
targetCallback,
methodName,
};
}
public applyPathsToRouterProxy<T extends HttpServer>(
router: T,
routePaths: RoutePathProperties[],
instanceWrapper: InstanceWrapper,
module: string,
basePath: string,
) {
(routePaths || []).forEach(pathProperties => {
const { path, requestMethod } = pathProperties;
this.applyCallbackToRouter(
router,
pathProperties,
instanceWrapper,
module,
basePath,
);
path.forEach(p =>
this.logger.log(ROUTE_MAPPED_MESSAGE(p, requestMethod)),
);
});
}
private applyCallbackToRouter<T extends HttpServer>(
router: T,
pathProperties: RoutePathProperties,
instanceWrapper: InstanceWrapper,
moduleKey: string,
basePath: string,
) {
const {
path: paths,
requestMethod,
targetCallback,
methodName,
} = pathProperties;
const { instance } = instanceWrapper;
const routerMethod = this.routerMethodFactory
.get(router, requestMethod)
.bind(router);
const stripSlash = (str: string) =>
str[str.length - 1] === '/' ? str.slice(0, str.length - 1) : str;
const isRequestScoped = !instanceWrapper.isDependencyTreeStatic();
const module = this.container.getModuleByKey(moduleKey);
if (isRequestScoped) {
const handler = this.createRequestScopedHandler(
instanceWrapper,
requestMethod,
module,
moduleKey,
methodName,
);
paths.forEach(path => {
const fullPath = stripSlash(basePath) + path;
routerMethod(stripSlash(fullPath) || '/', handler);
});
return;
}
const proxy = this.createCallbackProxy(
instance,
targetCallback,
methodName,
moduleKey,
requestMethod,
);
paths.forEach(path => {
const fullPath = stripSlash(basePath) + path;
routerMethod(stripSlash(fullPath) || '/', proxy);
});
}
private createCallbackProxy(
instance: Controller,
callback: RouterProxyCallback,
methodName: string,
module: string,
requestMethod: RequestMethod,
contextId = STATIC_CONTEXT,
inquirerId?: string,
) {
const executionContext = this.executionContextCreator.create(
instance,
callback,
methodName,
module,
requestMethod,
contextId,
inquirerId,
);
const exceptionFilter = this.exceptionsFilter.create(
instance,
callback,
module,
contextId,
inquirerId,
);
return this.routerProxy.createProxy(executionContext, exceptionFilter);
}
public createRequestScopedHandler(
instanceWrapper: InstanceWrapper,
requestMethod: RequestMethod,
module: Module,
moduleKey: string,
methodName: string,
) {
const { instance } = instanceWrapper;
const collection = module.controllers;
return async <TRequest, TResponse>(
req: TRequest,
res: TResponse,
next: () => void,
) => {
try {
const contextId = req[REQUEST_CONTEXT_ID] || createContextId();
this.registerRequestProvider(req, contextId);
const contextInstance = await this.injector.loadPerContext(
instance,
module,
collection,
contextId,
);
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 registerRequestProvider<T = any>(request: T, contextId: ContextId) {
const coreModuleRef = this.container.getInternalCoreModuleRef();
const wrapper = coreModuleRef.getProviderByKey(REQUEST);
wrapper.setInstanceByContextId(contextId, {
instance: request,
isResolved: true,
});
}
}