-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
nest-application.ts
297 lines (253 loc) · 8.83 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
import * as http from 'http';
import * as https from 'https';
import * as optional from 'optional';
import * as bodyParser from 'body-parser';
import iterate from 'iterare';
import {
CanActivate,
ExceptionFilter,
NestInterceptor,
OnModuleDestroy,
PipeTransform,
WebSocketAdapter,
} from '@nestjs/common';
import {
INestApplication,
INestMicroservice,
OnModuleInit,
} from '@nestjs/common';
import { Logger } from '@nestjs/common/services/logger.service';
import {
isNil,
isUndefined,
validatePath,
} from '@nestjs/common/utils/shared.utils';
import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface';
import { ExpressAdapter } from './adapters/express-adapter';
import { ApplicationConfig } from './application-config';
import { messages } from './constants';
import { NestContainer } from './injector/container';
import { Module } from './injector/module';
import { MiddlewaresModule } from './middlewares/middlewares-module';
import { Resolver } from './router/interfaces/resolver.interface';
import { RoutesResolver } from './router/routes-resolver';
import { MicroservicesPackageNotFoundException } from './errors/exceptions/microservices-package-not-found.exception';
import { MiddlewaresContainer } from './middlewares/container';
import { NestApplicationContext } from './nest-application-context';
import { HttpsOptions } from '@nestjs/common/interfaces/https-options.interface';
const { SocketModule } =
optional('@nestjs/websockets/socket-module') || ({} as any);
const { MicroservicesModule } =
optional('@nestjs/microservices/microservices-module') || ({} as any);
const { NestMicroservice } =
optional('@nestjs/microservices/nest-microservice') || ({} as any);
const { IoAdapter } =
optional('@nestjs/websockets/adapters/io-adapter') || ({} as any);
export class NestApplication extends NestApplicationContext
implements INestApplication {
private readonly logger = new Logger(NestApplication.name, true);
private readonly middlewaresModule = new MiddlewaresModule();
private readonly middlewaresContainer = new MiddlewaresContainer();
private readonly microservicesModule = MicroservicesModule
? new MicroservicesModule()
: null;
private readonly socketModule = SocketModule ? new SocketModule() : null;
private readonly httpServer: http.Server = null;
private readonly routesResolver: Resolver = null;
private readonly config: ApplicationConfig;
private readonly microservices = [];
private isInitialized = false;
constructor(
container: NestContainer,
private readonly express,
private readonly httpsOptions: HttpsOptions = null,
) {
super(container, [], null);
this.selectContextModule();
this.httpServer = this.createServer();
const ioAdapter = IoAdapter ? new IoAdapter(this.httpServer) : null;
this.config = new ApplicationConfig(ioAdapter);
this.routesResolver = new RoutesResolver(
container,
ExpressAdapter,
this.config,
);
}
public selectContextModule() {
const modules = this.container.getModules().values();
this.contextModule = modules.next().value;
}
public createServer(): any {
if (!this.httpsOptions) {
return http.createServer(this.express);
}
return https.createServer(this.httpsOptions, this.express);
}
public async setupModules() {
this.socketModule && this.socketModule.setup(this.container, this.config);
if (this.microservicesModule) {
this.microservicesModule.setup(this.container, this.config);
this.microservicesModule.setupClients(this.container);
}
await this.middlewaresModule.setup(
this.middlewaresContainer,
this.container,
this.config,
);
}
public async init() {
this.setupParserMiddlewares();
await this.setupModules();
await this.setupRouter();
this.callInitHook();
this.logger.log(messages.APPLICATION_READY);
this.isInitialized = true;
}
public setupParserMiddlewares() {
const parserMiddlewares = {
jsonParser: bodyParser.json(),
urlencodedParser: bodyParser.urlencoded({ extended: true }),
};
Object.keys(parserMiddlewares)
.filter(parser => !this.isMiddlewareApplied(this.express, parser))
.forEach(parserKey => this.express.use(parserMiddlewares[parserKey]));
}
public isMiddlewareApplied(app, name: string): boolean {
return (
!!app._router &&
!!app._router.stack.filter(
layer => layer && layer.handle && layer.handle.name === name,
).length
);
}
public async setupRouter() {
const router = ExpressAdapter.createRouter();
await this.setupMiddlewares(router);
this.routesResolver.resolve(router);
this.express.use(validatePath(this.config.getGlobalPrefix()), router);
}
public connectMicroservice(
config: MicroserviceConfiguration,
): INestMicroservice {
if (!NestMicroservice) {
throw new MicroservicesPackageNotFoundException();
}
const instance = new NestMicroservice(this.container as any, config as any);
instance.setupListeners();
instance.setIsInitialized(true);
instance.setIsInitHookCalled(true);
this.microservices.push(instance);
return instance;
}
public getMicroservices(): INestMicroservice[] {
return this.microservices;
}
public getHttpServer() {
return this.httpServer;
}
public startAllMicroservices(callback?: () => void) {
Promise.all(this.microservices.map(this.listenToPromise)).then(
() => callback && callback(),
);
}
public startAllMicroservicesAsync(): Promise<void> {
return new Promise(resolve => this.startAllMicroservices(resolve));
}
public use(...args) {
this.express.use(...args);
}
public engine(...args) {
this.express.engine(...args);
}
public set(...args) {
this.express.set(...args);
}
public async listen(port: number | string, callback?: () => void);
public async listen(
port: number | string,
hostname: string,
callback?: () => void,
);
public async listen(port: number | string, ...args) {
!this.isInitialized && (await this.init());
this.httpServer.listen(port, ...args);
return this.httpServer;
}
public listenAsync(port: number | string, hostname?: string): Promise<any> {
return new Promise(resolve => {
const server = this.listen(port, hostname, () => resolve(server));
});
}
public close() {
this.socketModule && this.socketModule.close();
this.httpServer && this.httpServer.close();
this.microservices.forEach(microservice => {
microservice.setIsTerminated(true);
microservice.close();
});
this.callDestroyHook();
}
public setGlobalPrefix(prefix: string) {
this.config.setGlobalPrefix(prefix);
}
public useWebSocketAdapter(adapter: WebSocketAdapter) {
this.config.setIoAdapter(adapter);
}
public useGlobalFilters(...filters: ExceptionFilter[]) {
this.config.useGlobalFilters(...filters);
}
public useGlobalPipes(...pipes: PipeTransform<any>[]) {
this.config.useGlobalPipes(...pipes);
}
public useGlobalInterceptors(...interceptors: NestInterceptor[]) {
this.config.useGlobalInterceptors(...interceptors);
}
public useGlobalGuards(...guards: CanActivate[]) {
this.config.useGlobalGuards(...guards);
}
private async setupMiddlewares(instance) {
await this.middlewaresModule.setupMiddlewares(
this.middlewaresContainer,
instance,
);
}
private listenToPromise(microservice: INestMicroservice) {
return new Promise(async (resolve, reject) => {
await microservice.listen(resolve);
});
}
private callInitHook() {
const modules = this.container.getModules();
modules.forEach(module => {
this.callModuleInitHook(module);
});
}
private callModuleInitHook(module: Module) {
const components = [...module.routes, ...module.components];
iterate(components)
.map(([key, { instance }]) => instance)
.filter(instance => !isNil(instance))
.filter(this.hasOnModuleInitHook)
.forEach(instance => (instance as OnModuleInit).onModuleInit());
}
private hasOnModuleInitHook(instance): instance is OnModuleInit {
return !isUndefined((instance as OnModuleInit).onModuleInit);
}
private callDestroyHook() {
const modules = this.container.getModules();
modules.forEach(module => {
this.callModuleDestroyHook(module);
});
}
private callModuleDestroyHook(module: Module) {
const components = [...module.routes, ...module.components];
iterate(components)
.map(([key, { instance }]) => instance)
.filter(instance => !isNil(instance))
.filter(this.hasOnModuleDestroyHook)
.forEach(instance => (instance as OnModuleDestroy).onModuleDestroy());
}
private hasOnModuleDestroyHook(instance): instance is OnModuleDestroy {
return !isUndefined((instance as OnModuleDestroy).onModuleDestroy);
}
}