-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
nest-application.ts
470 lines (413 loc) 路 13 KB
/
nest-application.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
import {
CanActivate,
ExceptionFilter,
HttpServer,
INestApplication,
INestMicroservice,
NestHybridApplicationOptions,
NestInterceptor,
PipeTransform,
VersioningOptions,
VersioningType,
WebSocketAdapter,
} from '@nestjs/common';
import {
GlobalPrefixOptions,
NestApplicationOptions,
} from '@nestjs/common/interfaces';
import {
CorsOptions,
CorsOptionsDelegate,
} from '@nestjs/common/interfaces/external/cors-options.interface';
import { Logger } from '@nestjs/common/services/logger.service';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import {
addLeadingSlash,
isFunction,
isObject,
isString,
} from '@nestjs/common/utils/shared.utils';
import { iterate } from 'iterare';
import { platform } from 'os';
import { AbstractHttpAdapter } from './adapters';
import { ApplicationConfig } from './application-config';
import { MESSAGES } from './constants';
import { optionalRequire } from './helpers/optional-require';
import { NestContainer } from './injector/container';
import { Injector } from './injector/injector';
import { GraphInspector } from './inspector/graph-inspector';
import { MiddlewareContainer } from './middleware/container';
import { MiddlewareModule } from './middleware/middleware-module';
import { mapToExcludeRoute } from './middleware/utils';
import { NestApplicationContext } from './nest-application-context';
import { Resolver } from './router/interfaces/resolver.interface';
import { RoutesResolver } from './router/routes-resolver';
const { SocketModule } = optionalRequire(
'@nestjs/websockets/socket-module',
() => require('@nestjs/websockets/socket-module'),
);
const { MicroservicesModule } = optionalRequire(
'@nestjs/microservices/microservices-module',
() => require('@nestjs/microservices/microservices-module'),
);
/**
* @publicApi
*/
export class NestApplication
extends NestApplicationContext<NestApplicationOptions>
implements INestApplication
{
protected readonly logger = new Logger(NestApplication.name, {
timestamp: true,
});
private readonly middlewareModule: MiddlewareModule;
private readonly middlewareContainer = new MiddlewareContainer(
this.container,
);
private readonly microservicesModule =
MicroservicesModule && new MicroservicesModule();
private readonly socketModule = SocketModule && new SocketModule();
private readonly routesResolver: Resolver;
private readonly microservices: any[] = [];
private httpServer: any;
private isListening = false;
constructor(
container: NestContainer,
private readonly httpAdapter: HttpServer,
private readonly config: ApplicationConfig,
private readonly graphInspector: GraphInspector,
appOptions: NestApplicationOptions = {},
) {
super(container, appOptions);
this.selectContextModule();
this.registerHttpServer();
this.injector = new Injector({ preview: this.appOptions.preview });
this.middlewareModule = new MiddlewareModule();
this.routesResolver = new RoutesResolver(
this.container,
this.config,
this.injector,
this.graphInspector,
);
}
protected async dispose(): Promise<void> {
this.socketModule && (await this.socketModule.close());
this.microservicesModule && (await this.microservicesModule.close());
this.httpAdapter && (await this.httpAdapter.close());
await Promise.all(
iterate(this.microservices).map(async microservice => {
microservice.setIsTerminated(true);
await microservice.close();
}),
);
}
public getHttpAdapter(): AbstractHttpAdapter {
return this.httpAdapter as AbstractHttpAdapter;
}
public registerHttpServer() {
this.httpServer = this.createServer();
}
public getUnderlyingHttpServer<T>(): T {
return this.httpAdapter.getHttpServer();
}
public applyOptions() {
if (!this.appOptions || !this.appOptions.cors) {
return undefined;
}
const passCustomOptions =
isObject(this.appOptions.cors) || isFunction(this.appOptions.cors);
if (!passCustomOptions) {
return this.enableCors();
}
return this.enableCors(
this.appOptions.cors as CorsOptions | CorsOptionsDelegate<any>,
);
}
public createServer<T = any>(): T {
this.httpAdapter.initHttpServer(this.appOptions);
return this.httpAdapter.getHttpServer() as T;
}
public async registerModules() {
this.registerWsModule();
if (this.microservicesModule) {
this.microservicesModule.register(
this.container,
this.graphInspector,
this.config,
this.appOptions,
);
this.microservicesModule.setupClients(this.container);
}
await this.middlewareModule.register(
this.middlewareContainer,
this.container,
this.config,
this.injector,
this.httpAdapter,
this.graphInspector,
this.appOptions,
);
}
public registerWsModule() {
if (!this.socketModule) {
return;
}
this.socketModule.register(
this.container,
this.config,
this.graphInspector,
this.appOptions,
this.httpServer,
);
}
public async init(): Promise<this> {
if (this.isInitialized) {
return this;
}
this.applyOptions();
await this.httpAdapter?.init();
const useBodyParser =
this.appOptions && this.appOptions.bodyParser !== false;
useBodyParser && this.registerParserMiddleware();
await this.registerModules();
await this.registerRouter();
await this.callInitHook();
await this.registerRouterHooks();
await this.callBootstrapHook();
this.isInitialized = true;
this.logger.log(MESSAGES.APPLICATION_READY);
return this;
}
public registerParserMiddleware() {
const prefix = this.config.getGlobalPrefix();
const rawBody = !!this.appOptions?.rawBody;
this.httpAdapter.registerParserMiddleware(prefix, rawBody);
}
public async registerRouter() {
await this.registerMiddleware(this.httpAdapter);
const prefix = this.config.getGlobalPrefix();
const basePath = addLeadingSlash(prefix);
this.routesResolver.resolve(this.httpAdapter, basePath);
}
public async registerRouterHooks() {
this.routesResolver.registerNotFoundHandler();
this.routesResolver.registerExceptionHandler();
}
public connectMicroservice<T extends object>(
microserviceOptions: T,
hybridAppOptions: NestHybridApplicationOptions = {},
): INestMicroservice {
const { NestMicroservice } = loadPackage(
'@nestjs/microservices',
'NestFactory',
() => require('@nestjs/microservices'),
);
const { inheritAppConfig } = hybridAppOptions;
const applicationConfig = inheritAppConfig
? this.config
: new ApplicationConfig();
const instance = new NestMicroservice(
this.container,
microserviceOptions,
this.graphInspector,
applicationConfig,
);
instance.registerListeners();
instance.setIsInitialized(true);
instance.setIsInitHookCalled(true);
this.microservices.push(instance);
return instance;
}
public getMicroservices(): INestMicroservice[] {
return this.microservices;
}
public getHttpServer() {
return this.httpServer;
}
public async startAllMicroservices(): Promise<this> {
this.assertNotInPreviewMode('startAllMicroservices');
await Promise.all(this.microservices.map(msvc => msvc.listen()));
return this;
}
public use(...args: [any, any?]): this {
this.httpAdapter.use(...args);
return this;
}
public useBodyParser(...args: [any, any?]): this {
if (!('useBodyParser' in this.httpAdapter)) {
this.logger.warn('Your HTTP Adapter does not support `.useBodyParser`.');
return this;
}
const [parserType, ...otherArgs] = args;
const rawBody = !!this.appOptions.rawBody;
this.httpAdapter.useBodyParser(...[parserType, rawBody, ...otherArgs]);
return this;
}
public enableCors(options?: CorsOptions | CorsOptionsDelegate<any>): void {
this.httpAdapter.enableCors(options);
}
public enableVersioning(
options: VersioningOptions = { type: VersioningType.URI },
): this {
this.config.enableVersioning(options);
return this;
}
public async listen(port: number | string): Promise<any>;
public async listen(port: number | string, hostname: string): Promise<any>;
public async listen(port: number | string, ...args: any[]): Promise<any> {
this.assertNotInPreviewMode('listen');
!this.isInitialized && (await this.init());
return new Promise((resolve, reject) => {
const errorHandler = (e: any) => {
this.logger.error(e?.toString?.());
reject(e);
};
this.httpServer.once('error', errorHandler);
const isCallbackInOriginalArgs = isFunction(args[args.length - 1]);
const listenFnArgs = isCallbackInOriginalArgs
? args.slice(0, args.length - 1)
: args;
this.httpAdapter.listen(
port,
...listenFnArgs,
(...originalCallbackArgs: unknown[]) => {
if (this.appOptions?.autoFlushLogs ?? true) {
this.flushLogs();
}
if (originalCallbackArgs[0] instanceof Error) {
return reject(originalCallbackArgs[0]);
}
const address = this.httpServer.address();
if (address) {
this.httpServer.removeListener('error', errorHandler);
this.isListening = true;
resolve(this.httpServer);
}
if (isCallbackInOriginalArgs) {
args[args.length - 1](...originalCallbackArgs);
}
},
);
});
}
public async getUrl(): Promise<string> {
return new Promise((resolve, reject) => {
if (!this.isListening) {
this.logger.error(MESSAGES.CALL_LISTEN_FIRST);
reject(MESSAGES.CALL_LISTEN_FIRST);
return;
}
const address = this.httpServer.address();
resolve(this.formatAddress(address));
});
}
private formatAddress(address: any): string {
if (isString(address)) {
if (platform() === 'win32') {
return address;
}
const basePath = encodeURIComponent(address);
return `${this.getProtocol()}+unix://${basePath}`;
}
let host = this.host();
if (address && address.family === 'IPv6') {
if (host === '::') {
host = '[::1]';
} else {
host = `[${host}]`;
}
} else if (host === '0.0.0.0') {
host = '127.0.0.1';
}
return `${this.getProtocol()}://${host}:${address.port}`;
}
public setGlobalPrefix(prefix: string, options?: GlobalPrefixOptions): this {
this.config.setGlobalPrefix(prefix);
if (options) {
const exclude = options?.exclude
? mapToExcludeRoute(options.exclude)
: [];
this.config.setGlobalPrefixOptions({
...options,
exclude,
});
}
return this;
}
public useWebSocketAdapter(adapter: WebSocketAdapter): this {
this.config.setIoAdapter(adapter);
return this;
}
public useGlobalFilters(...filters: ExceptionFilter[]): this {
this.config.useGlobalFilters(...filters);
filters.forEach(item =>
this.graphInspector.insertOrphanedEnhancer({
subtype: 'filter',
ref: item,
}),
);
return this;
}
public useGlobalPipes(...pipes: PipeTransform<any>[]): this {
this.config.useGlobalPipes(...pipes);
pipes.forEach(item =>
this.graphInspector.insertOrphanedEnhancer({
subtype: 'pipe',
ref: item,
}),
);
return this;
}
public useGlobalInterceptors(...interceptors: NestInterceptor[]): this {
this.config.useGlobalInterceptors(...interceptors);
interceptors.forEach(item =>
this.graphInspector.insertOrphanedEnhancer({
subtype: 'interceptor',
ref: item,
}),
);
return this;
}
public useGlobalGuards(...guards: CanActivate[]): this {
this.config.useGlobalGuards(...guards);
guards.forEach(item =>
this.graphInspector.insertOrphanedEnhancer({
subtype: 'guard',
ref: item,
}),
);
return this;
}
public useStaticAssets(options: any): this;
public useStaticAssets(path: string, options?: any): this;
public useStaticAssets(pathOrOptions: any, options?: any): this {
this.httpAdapter.useStaticAssets &&
this.httpAdapter.useStaticAssets(pathOrOptions, options);
return this;
}
public setBaseViewsDir(path: string | string[]): this {
this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path);
return this;
}
public setViewEngine(engineOrOptions: any): this {
this.httpAdapter.setViewEngine &&
this.httpAdapter.setViewEngine(engineOrOptions);
return this;
}
private host(): string | undefined {
const address = this.httpServer.address();
if (isString(address)) {
return undefined;
}
return address && address.address;
}
private getProtocol(): 'http' | 'https' {
return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
}
private async registerMiddleware(instance: any) {
await this.middlewareModule.registerMiddleware(
this.middlewareContainer,
instance,
);
}
}