UNPKG

9.33 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);
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 &&
86 this.registerParserMiddleware(this.config.getGlobalPrefix());
87 await this.registerModules();
88 await this.registerRouter();
89 await this.callInitHook();
90 await this.registerRouterHooks();
91 await this.callBootstrapHook();
92 this.isInitialized = true;
93 this.logger.log(constants_1.MESSAGES.APPLICATION_READY);
94 return this;
95 }
96 registerParserMiddleware(prefix = '/') {
97 this.httpAdapter.registerParserMiddleware(prefix);
98 }
99 async registerRouter() {
100 await this.registerMiddleware(this.httpAdapter);
101 const prefix = this.config.getGlobalPrefix();
102 const basePath = shared_utils_1.validatePath(prefix);
103 this.routesResolver.resolve(this.httpAdapter, basePath);
104 }
105 async registerRouterHooks() {
106 this.routesResolver.registerNotFoundHandler();
107 this.routesResolver.registerExceptionHandler();
108 }
109 connectMicroservice(options) {
110 const { NestMicroservice } = load_package_util_1.loadPackage('@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'));
111 const applicationConfig = new application_config_1.ApplicationConfig();
112 const instance = new NestMicroservice(this.container, options, applicationConfig);
113 instance.registerListeners();
114 instance.setIsInitialized(true);
115 instance.setIsInitHookCalled(true);
116 this.microservices.push(instance);
117 return instance;
118 }
119 getMicroservices() {
120 return this.microservices;
121 }
122 getHttpServer() {
123 return this.httpServer;
124 }
125 startAllMicroservices(callback) {
126 Promise.all(this.microservices.map(this.listenToPromise)).then(() => callback && callback());
127 return this;
128 }
129 startAllMicroservicesAsync() {
130 return new Promise(resolve => this.startAllMicroservices(resolve));
131 }
132 use(...args) {
133 this.httpAdapter.use(...args);
134 return this;
135 }
136 enableCors(options) {
137 this.httpAdapter.enableCors(options, this.config.getGlobalPrefix());
138 }
139 async listen(port, ...args) {
140 !this.isInitialized && (await this.init());
141 this.httpAdapter.listen(port, ...args);
142 this.isListening = true;
143 return this.httpServer;
144 }
145 listenAsync(port, hostname) {
146 return new Promise(resolve => {
147 const server = this.listen(port, hostname, () => resolve(server));
148 });
149 }
150 async getUrl() {
151 return new Promise((resolve, reject) => {
152 if (!this.isListening) {
153 this.logger.error(constants_1.MESSAGES.CALL_LISTEN_FIRST);
154 reject(constants_1.MESSAGES.CALL_LISTEN_FIRST);
155 }
156 this.httpServer.on('listening', () => {
157 const address = this.httpServer.address();
158 if (typeof address === 'string') {
159 if (os_1.platform() === 'win32') {
160 return address;
161 }
162 const basePath = encodeURIComponent(address);
163 return `${this.getProtocol()}+unix://${basePath}`;
164 }
165 let host = this.host();
166 if (address && address.family === 'IPv6') {
167 if (host === '::') {
168 host = '[::1]';
169 }
170 else {
171 host = `[${host}]`;
172 }
173 }
174 else if (host === '0.0.0.0') {
175 host = '127.0.0.1';
176 }
177 resolve(`${this.getProtocol()}://${host}:${address.port}`);
178 });
179 });
180 }
181 setGlobalPrefix(prefix) {
182 this.config.setGlobalPrefix(prefix);
183 return this;
184 }
185 useWebSocketAdapter(adapter) {
186 this.config.setIoAdapter(adapter);
187 return this;
188 }
189 useGlobalFilters(...filters) {
190 this.config.useGlobalFilters(...filters);
191 return this;
192 }
193 useGlobalPipes(...pipes) {
194 this.config.useGlobalPipes(...pipes);
195 return this;
196 }
197 useGlobalInterceptors(...interceptors) {
198 this.config.useGlobalInterceptors(...interceptors);
199 return this;
200 }
201 useGlobalGuards(...guards) {
202 this.config.useGlobalGuards(...guards);
203 return this;
204 }
205 useStaticAssets(pathOrOptions, options) {
206 this.httpAdapter.useStaticAssets &&
207 this.httpAdapter.useStaticAssets(pathOrOptions, options);
208 return this;
209 }
210 setBaseViewsDir(path) {
211 this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path);
212 return this;
213 }
214 setViewEngine(engineOrOptions) {
215 this.httpAdapter.setViewEngine &&
216 this.httpAdapter.setViewEngine(engineOrOptions);
217 return this;
218 }
219 host() {
220 const address = this.httpServer.address();
221 if (typeof address === 'string') {
222 return undefined;
223 }
224 return address && address.address;
225 }
226 getProtocol() {
227 return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
228 }
229 async registerMiddleware(instance) {
230 await this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
231 }
232 listenToPromise(microservice) {
233 return new Promise(async (resolve, reject) => {
234 await microservice.listen(resolve);
235 });
236 }
237}
238exports.NestApplication = NestApplication;