forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnest-application.ts
More file actions
220 lines (184 loc) · 7.72 KB
/
Copy pathnest-application.ts
File metadata and controls
220 lines (184 loc) · 7.72 KB
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
import * as http from 'http';
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';
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 implements INestApplication {
private readonly middlewaresContainer = new MiddlewaresContainer();
private readonly logger = new Logger(NestApplication.name, true);
private readonly httpServer: http.Server = null;
private readonly routesResolver: Resolver = null;
private readonly config: ApplicationConfig;
private readonly microservices = [];
private isInitialized = false;
constructor(
private readonly container: NestContainer,
private readonly express,
) {
this.setupParserMiddlewares();
this.httpServer = http.createServer(express);
const ioAdapter = IoAdapter ? new IoAdapter(this.httpServer) : null;
this.config = new ApplicationConfig(ioAdapter);
this.routesResolver = new RoutesResolver(
container, ExpressAdapter, this.config,
);
}
public setupParserMiddlewares() {
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: true }));
}
public async setupModules() {
SocketModule && SocketModule.setup(this.container, this.config);
if (MicroservicesModule) {
MicroservicesModule.setup(this.container, this.config);
MicroservicesModule.setupClients(this.container);
}
await MiddlewaresModule.setup(
this.middlewaresContainer,
this.container,
this.config,
);
}
public async init() {
await this.setupModules();
await this.setupRouter();
this.callInitHook();
this.logger.log(messages.APPLICATION_READY);
this.isInitialized = true;
}
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 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(requestHandler) {
this.express.use(requestHandler);
}
public async listen(port: number, callback?: () => void);
public async listen(port: number, hostname: string, callback?: () => void);
public async listen(port: number, ...args) {
(!this.isInitialized) && await this.init();
this.httpServer.listen(port, ...args);
return this.httpServer;
}
public listenAsync(port: number, hostname?: string): Promise<any> {
return new Promise((resolve) => {
const server = this.listen(port, hostname, () => resolve(server));
});
}
public close() {
SocketModule && 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 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);
}
}