-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
Copy pathexpress-adapter.ts
486 lines (423 loc) · 14 KB
/
express-adapter.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
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
import {
HttpStatus,
InternalServerErrorException,
Logger,
RequestMethod,
StreamableFile,
VERSION_NEUTRAL,
VersioningOptions,
VersioningType,
} from '@nestjs/common';
import { VersionValue } from '@nestjs/common/interfaces';
import {
CorsOptions,
CorsOptionsDelegate,
} from '@nestjs/common/interfaces/external/cors-options.interface';
import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface';
import {
isFunction,
isNil,
isObject,
isString,
isUndefined,
} from '@nestjs/common/utils/shared.utils';
import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter';
import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory';
import { LegacyRouteConverter } from '@nestjs/core/router/legacy-route-converter';
import * as bodyparser from 'body-parser';
import {
json as bodyParserJson,
urlencoded as bodyParserUrlencoded,
} from 'body-parser';
import * as cors from 'cors';
import * as express from 'express';
import type { Server } from 'http';
import * as http from 'http';
import * as https from 'https';
import { pathToRegexp } from 'path-to-regexp';
import { Duplex, pipeline } from 'stream';
import { NestExpressBodyParserOptions } from '../interfaces/nest-express-body-parser-options.interface';
import { NestExpressBodyParserType } from '../interfaces/nest-express-body-parser.interface';
import { ServeStaticOptions } from '../interfaces/serve-static-options.interface';
import { getBodyParserOptions } from './utils/get-body-parser-options.util';
type VersionedRoute = <
TRequest extends Record<string, any> = any,
TResponse = any,
>(
req: TRequest,
res: TResponse,
next: () => void,
) => any;
/**
* @publicApi
*/
export class ExpressAdapter extends AbstractHttpAdapter<
http.Server | https.Server
> {
private readonly routerMethodFactory = new RouterMethodFactory();
private readonly logger = new Logger(ExpressAdapter.name);
private readonly openConnections = new Set<Duplex>();
constructor(instance?: any) {
super(instance || express());
}
public reply(response: any, body: any, statusCode?: number) {
if (statusCode) {
response.status(statusCode);
}
if (isNil(body)) {
return response.send();
}
if (body instanceof StreamableFile) {
const streamHeaders = body.getHeaders();
if (
response.getHeader('Content-Type') === undefined &&
streamHeaders.type !== undefined
) {
response.setHeader('Content-Type', streamHeaders.type);
}
if (
response.getHeader('Content-Disposition') === undefined &&
streamHeaders.disposition !== undefined
) {
response.setHeader('Content-Disposition', streamHeaders.disposition);
}
if (
response.getHeader('Content-Length') === undefined &&
streamHeaders.length !== undefined
) {
response.setHeader('Content-Length', streamHeaders.length);
}
return pipeline(
body.getStream().once('error', (err: Error) => {
body.errorHandler(err, response);
}),
response,
(err: any) => {
if (err) {
body.errorLogger(err);
}
},
);
}
const responseContentType = response.getHeader('Content-Type');
if (
typeof responseContentType === 'string' &&
!responseContentType.startsWith('application/json') &&
body?.statusCode >= HttpStatus.BAD_REQUEST
) {
this.logger.warn(
"Content-Type doesn't match Reply body, you might need a custom ExceptionFilter for non-JSON responses",
);
response.setHeader('Content-Type', 'application/json');
}
return isObject(body) ? response.json(body) : response.send(String(body));
}
public status(response: any, statusCode: number) {
return response.status(statusCode);
}
public end(response: any, message?: string) {
return response.end(message);
}
public render(response: any, view: string, options: any) {
return response.render(view, options);
}
public redirect(response: any, statusCode: number, url: string) {
return response.redirect(statusCode, url);
}
public setErrorHandler(handler: Function, prefix?: string) {
return this.use(handler);
}
public setNotFoundHandler(handler: Function, prefix?: string) {
return this.use(handler);
}
public isHeadersSent(response: any): boolean {
return response.headersSent;
}
public getHeader(response: any, name: string) {
return response.get(name);
}
public setHeader(response: any, name: string, value: string) {
return response.set(name, value);
}
public appendHeader(response: any, name: string, value: string) {
return response.append(name, value);
}
public normalizePath(path: string): string {
try {
const convertedPath = LegacyRouteConverter.tryConvert(path);
// Call "pathToRegexp" to trigger a TypeError if the path is invalid
pathToRegexp(convertedPath);
return convertedPath;
} catch (e) {
if (e instanceof TypeError) {
LegacyRouteConverter.printError(path);
}
throw e;
}
}
public listen(port: string | number, callback?: () => void): Server;
public listen(
port: string | number,
hostname: string,
callback?: () => void,
): Server;
public listen(port: any, ...args: any[]): Server {
return this.httpServer.listen(port, ...args);
}
public close() {
this.closeOpenConnections();
if (!this.httpServer) {
return undefined;
}
return new Promise(resolve => this.httpServer.close(resolve));
}
public set(...args: any[]) {
return this.instance.set(...args);
}
public enable(...args: any[]) {
return this.instance.enable(...args);
}
public disable(...args: any[]) {
return this.instance.disable(...args);
}
public engine(...args: any[]) {
return this.instance.engine(...args);
}
public useStaticAssets(path: string, options: ServeStaticOptions) {
if (options && options.prefix) {
return this.use(options.prefix, express.static(path, options));
}
return this.use(express.static(path, options));
}
public setBaseViewsDir(path: string | string[]) {
return this.set('views', path);
}
public setViewEngine(engine: string) {
return this.set('view engine', engine);
}
public getRequestHostname(request: any): string {
return request.hostname;
}
public getRequestMethod(request: any): string {
return request.method;
}
public getRequestUrl(request: any): string {
return request.originalUrl;
}
public enableCors(options: CorsOptions | CorsOptionsDelegate<any>) {
return this.use(cors(options as any));
}
public createMiddlewareFactory(
requestMethod: RequestMethod,
): (path: string, callback: Function) => any {
return (path: string, callback: Function) => {
try {
const convertedPath = LegacyRouteConverter.tryConvert(path);
return this.routerMethodFactory
.get(this.instance, requestMethod)
.call(this.instance, convertedPath, callback);
} catch (e) {
if (e instanceof TypeError) {
LegacyRouteConverter.printError(path);
}
throw e;
}
};
}
public initHttpServer(options: NestApplicationOptions) {
const isHttpsEnabled = options && options.httpsOptions;
if (isHttpsEnabled) {
this.httpServer = https.createServer(
options.httpsOptions!,
this.getInstance(),
);
} else {
this.httpServer = http.createServer(this.getInstance());
}
if (options?.forceCloseConnections) {
this.trackOpenConnections();
}
}
public registerParserMiddleware(prefix?: string, rawBody?: boolean) {
const bodyParserJsonOptions = getBodyParserOptions(rawBody!);
const bodyParserUrlencodedOptions = getBodyParserOptions(rawBody!, {
extended: true,
});
const parserMiddleware = {
jsonParser: bodyParserJson(bodyParserJsonOptions),
urlencodedParser: bodyParserUrlencoded(bodyParserUrlencodedOptions),
};
Object.keys(parserMiddleware)
.filter(parser => !this.isMiddlewareApplied(parser))
.forEach(parserKey => this.use(parserMiddleware[parserKey]));
}
public useBodyParser<
Options extends NestExpressBodyParserOptions = NestExpressBodyParserOptions,
>(
type: NestExpressBodyParserType,
rawBody: boolean,
options?: Omit<Options, 'verify'>,
): this {
const parserOptions = getBodyParserOptions<Options>(rawBody, options);
const parser = bodyparser[type](parserOptions);
this.use(parser);
return this;
}
public setLocal(key: string, value: any) {
this.instance.locals[key] = value;
return this;
}
public getType(): string {
return 'express';
}
public applyVersionFilter(
handler: Function,
version: VersionValue,
versioningOptions: VersioningOptions,
): VersionedRoute {
const callNextHandler: VersionedRoute = (req, res, next) => {
if (!next) {
throw new InternalServerErrorException(
'HTTP adapter does not support filtering on version',
);
}
return next();
};
if (
version === VERSION_NEUTRAL ||
// URL Versioning is done via the path, so the filter continues forward
versioningOptions.type === VersioningType.URI
) {
const handlerForNoVersioning: VersionedRoute = (req, res, next) =>
handler(req, res, next);
return handlerForNoVersioning;
}
// Custom Extractor Versioning Handler
if (versioningOptions.type === VersioningType.CUSTOM) {
const handlerForCustomVersioning: VersionedRoute = (req, res, next) => {
const extractedVersion = versioningOptions.extractor(req);
if (Array.isArray(version)) {
if (
Array.isArray(extractedVersion) &&
version.filter(v => extractedVersion.includes(v as string)).length
) {
return handler(req, res, next);
}
if (
isString(extractedVersion) &&
version.includes(extractedVersion)
) {
return handler(req, res, next);
}
} else if (isString(version)) {
// Known bug here - if there are multiple versions supported across separate
// handlers/controllers, we can't select the highest matching handler.
// Since this code is evaluated per-handler, then we can't see if the highest
// specified version exists in a different handler.
if (
Array.isArray(extractedVersion) &&
extractedVersion.includes(version)
) {
return handler(req, res, next);
}
if (isString(extractedVersion) && version === extractedVersion) {
return handler(req, res, next);
}
}
return callNextHandler(req, res, next);
};
return handlerForCustomVersioning;
}
// Media Type (Accept Header) Versioning Handler
if (versioningOptions.type === VersioningType.MEDIA_TYPE) {
const handlerForMediaTypeVersioning: VersionedRoute = (
req,
res,
next,
) => {
const MEDIA_TYPE_HEADER = 'Accept';
const acceptHeaderValue: string | undefined =
req.headers?.[MEDIA_TYPE_HEADER] ||
req.headers?.[MEDIA_TYPE_HEADER.toLowerCase()];
const acceptHeaderVersionParameter = acceptHeaderValue
? acceptHeaderValue.split(';')[1]
: undefined;
// No version was supplied
if (isUndefined(acceptHeaderVersionParameter)) {
if (Array.isArray(version)) {
if (version.includes(VERSION_NEUTRAL)) {
return handler(req, res, next);
}
}
} else {
const headerVersion = acceptHeaderVersionParameter.split(
versioningOptions.key,
)[1];
if (Array.isArray(version)) {
if (version.includes(headerVersion)) {
return handler(req, res, next);
}
} else if (isString(version)) {
if (version === headerVersion) {
return handler(req, res, next);
}
}
}
return callNextHandler(req, res, next);
};
return handlerForMediaTypeVersioning;
}
// Header Versioning Handler
if (versioningOptions.type === VersioningType.HEADER) {
const handlerForHeaderVersioning: VersionedRoute = (req, res, next) => {
const customHeaderVersionParameter: string | undefined =
req.headers?.[versioningOptions.header] ||
req.headers?.[versioningOptions.header.toLowerCase()];
// No version was supplied
if (isUndefined(customHeaderVersionParameter)) {
if (Array.isArray(version)) {
if (version.includes(VERSION_NEUTRAL)) {
return handler(req, res, next);
}
}
} else {
if (Array.isArray(version)) {
if (version.includes(customHeaderVersionParameter)) {
return handler(req, res, next);
}
} else if (isString(version)) {
if (version === customHeaderVersionParameter) {
return handler(req, res, next);
}
}
}
return callNextHandler(req, res, next);
};
return handlerForHeaderVersioning;
}
throw new Error('Unsupported versioning options');
}
private trackOpenConnections() {
this.httpServer.on('connection', (socket: Duplex) => {
this.openConnections.add(socket);
socket.on('close', () => this.openConnections.delete(socket));
});
}
private closeOpenConnections() {
for (const socket of this.openConnections) {
socket.destroy();
this.openConnections.delete(socket);
}
}
private isMiddlewareApplied(name: string): boolean {
const app = this.getInstance();
return (
!!app._router &&
!!app._router.stack &&
isFunction(app._router.stack.filter) &&
app._router.stack.some(
(layer: any) => layer && layer.handle && layer.handle.name === name,
)
);
}
}