UNPKG

9.28 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const logger_service_1 = require("@nestjs/common/services/logger.service");
4const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
5const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6const iterare_1 = require("iterare");
7const os_1 = require("os");
8const application_config_1 = require("./application-config");
9const constants_1 = require("./constants");
10const optional_require_1 = require("./helpers/optional-require");
11const container_1 = require("./middleware/container");
12const middleware_module_1 = require("./middleware/middleware-module");
13const nest_application_context_1 = require("./nest-application-context");
14const routes_resolver_1 = require("./router/routes-resolver");
15const { SocketModule } = optional_require_1.optionalRequire('@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'));
16const { MicroservicesModule, } = optional_require_1.optionalRequire('@nestjs/microservices/microservices-module', () => require('@nestjs/microservices/microservices-module'));
17/**
18 * @publicApi
19 */
20class NestApplication extends nest_application_context_1.NestApplicationContext {
21 constructor(container, httpAdapter, config, appOptions = {}) {
22 super(container);
23 this.httpAdapter = httpAdapter;
24 this.config = config;
25 this.appOptions = appOptions;
26 this.logger = new logger_service_1.Logger(NestApplication.name, true);
27 this.middlewareModule = new middleware_module_1.MiddlewareModule();
28 this.middlewareContainer = new container_1.MiddlewareContainer();
29 this.microservicesModule = MicroservicesModule
30 ? new MicroservicesModule()
31 : null;
32 this.socketModule = SocketModule ? new SocketModule() : null;
33 this.microservices = [];
34 this.isListening = false;
35 this.applyOptions();
36 this.selectContextModule();
37 this.registerHttpServer();
38 this.routesResolver = new routes_resolver_1.RoutesResolver(this.container, this.config, this.injector);
39 }
40 async dispose() {
41 this.socketModule && (await this.socketModule.close());
42 this.httpAdapter && (await this.httpAdapter.close());
43 await Promise.all(iterare_1.default(this.microservices).map(async (microservice) => {
44 microservice.setIsTerminated(true);
45 await microservice.close();
46 }));
47 }
48 getHttpAdapter() {
49 return this.httpAdapter;
50 }
51 registerHttpServer() {
52 this.httpServer = this.createServer();
53 }
54 getUnderlyingHttpServer() {
55 return this.httpAdapter.getHttpServer();
56 }
57 applyOptions() {
58 if (!this.appOptions || !this.appOptions.cors) {
59 return undefined;
60 }
61 const isCorsOptionsObj = shared_utils_1.isObject(this.appOptions.cors);
62 if (!isCorsOptionsObj) {
63 return this.enableCors();
64 }
65 this.enableCors(this.appOptions.cors);
66 }
67 createServer() {
68 this.httpAdapter.initHttpServer(this.appOptions);
69 return this.httpAdapter.getHttpServer();
70 }
71 async registerModules() {
72 this.registerWsModule();
73 if (this.microservicesModule) {
74 this.microservicesModule.register(this.container, this.config);
75 this.microservicesModule.setupClients(this.container);
76 }
77 await this.middlewareModule.register(this.middlewareContainer, this.container, this.config, this.injector);
78 }
79 registerWsModule() {
80 if (!this.socketModule) {
81 return;
82 }
83 this.socketModule.register(this.container, this.config, this.httpServer);
84 }
85 async init() {
86 const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false;
87 useBodyParser && this.registerParserMiddleware();
88 await this.registerModules();
89 await this.registerRouter();
90 await this.callInitHook();
91 await this.registerRouterHooks();
92 await this.callBootstrapHook();
93 this.isInitialized = true;
94 this.logger.log(constants_1.MESSAGES.APPLICATION_READY);
95 return this;
96 }
97 registerParserMiddleware() {
98 this.httpAdapter.registerParserMiddleware();
99 }
100 async registerRouter() {
101 await this.registerMiddleware(this.httpAdapter);
102 const prefix = this.config.getGlobalPrefix();
103 const basePath = shared_utils_1.validatePath(prefix);
104 this.routesResolver.resolve(this.httpAdapter, basePath);
105 }
106 async registerRouterHooks() {
107 this.routesResolver.registerNotFoundHandler();
108 this.routesResolver.registerExceptionHandler();
109 }
110 connectMicroservice(options) {
111 const { NestMicroservice } = load_package_util_1.loadPackage('@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'));
112 const applicationConfig = new application_config_1.ApplicationConfig();
113 const instance = new NestMicroservice(this.container, options, applicationConfig);
114 instance.registerListeners();
115 instance.setIsInitialized(true);
116 instance.setIsInitHookCalled(true);
117 this.microservices.push(instance);
118 return instance;
119 }
120 getMicroservices() {
121 return this.microservices;
122 }
123 getHttpServer() {
124 return this.httpServer;
125 }
126 startAllMicroservices(callback) {
127 Promise.all(this.microservices.map(this.listenToPromise)).then(() => callback && callback());
128 return this;
129 }
130 startAllMicroservicesAsync() {
131 return new Promise(resolve => this.startAllMicroservices(resolve));
132 }
133 use(...args) {
134 this.httpAdapter.use(...args);
135 return this;
136 }
137 enableCors(options) {
138 this.httpAdapter.enableCors(options);
139 return this;
140 }
141 async listen(port, ...args) {
142 !this.isInitialized && (await this.init());
143 this.httpAdapter.listen(port, ...args);
144 this.isListening = true;
145 return this.httpServer;
146 }
147 listenAsync(port, hostname) {
148 return new Promise(resolve => {
149 const server = this.listen(port, hostname, () => resolve(server));
150 });
151 }
152 async getUrl() {
153 return new Promise((resolve, reject) => {
154 if (!this.isListening) {
155 this.logger.error(constants_1.MESSAGES.CALL_LISTEN_FIRST);
156 reject(constants_1.MESSAGES.CALL_LISTEN_FIRST);
157 }
158 this.httpServer.on('listening', () => {
159 const address = this.httpServer.address();
160 if (typeof address === 'string') {
161 if (os_1.platform() === 'win32') {
162 return address;
163 }
164 const basePath = encodeURIComponent(address);
165 return `${this.getProtocol()}+unix://${basePath}`;
166 }
167 let host = this.host();
168 if (address && address.family === 'IPv6') {
169 if (host === '::') {
170 host = '[::1]';
171 }
172 else {
173 host = `[${host}]`;
174 }
175 }
176 else if (host === '0.0.0.0') {
177 host = '127.0.0.1';
178 }
179 resolve(`${this.getProtocol()}://${host}:${address.port}`);
180 });
181 });
182 }
183 setGlobalPrefix(prefix) {
184 this.config.setGlobalPrefix(prefix);
185 return this;
186 }
187 useWebSocketAdapter(adapter) {
188 this.config.setIoAdapter(adapter);
189 return this;
190 }
191 useGlobalFilters(...filters) {
192 this.config.useGlobalFilters(...filters);
193 return this;
194 }
195 useGlobalPipes(...pipes) {
196 this.config.useGlobalPipes(...pipes);
197 return this;
198 }
199 useGlobalInterceptors(...interceptors) {
200 this.config.useGlobalInterceptors(...interceptors);
201 return this;
202 }
203 useGlobalGuards(...guards) {
204 this.config.useGlobalGuards(...guards);
205 return this;
206 }
207 useStaticAssets(pathOrOptions, options) {
208 this.httpAdapter.useStaticAssets &&
209 this.httpAdapter.useStaticAssets(pathOrOptions, options);
210 return this;
211 }
212 setBaseViewsDir(path) {
213 this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path);
214 return this;
215 }
216 setViewEngine(engineOrOptions) {
217 this.httpAdapter.setViewEngine &&
218 this.httpAdapter.setViewEngine(engineOrOptions);
219 return this;
220 }
221 host() {
222 const address = this.httpServer.address();
223 if (typeof address === 'string') {
224 return undefined;
225 }
226 return address && address.address;
227 }
228 getProtocol() {
229 return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
230 }
231 async registerMiddleware(instance) {
232 await this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
233 }
234 listenToPromise(microservice) {
235 return new Promise(async (resolve, reject) => {
236 await microservice.listen(resolve);
237 });
238 }
239}
240exports.NestApplication = NestApplication;