UNPKG

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