UNPKG

12 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.NestApplication = void 0;
4const common_1 = require("@nestjs/common");
5const logger_service_1 = require("@nestjs/common/services/logger.service");
6const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
7const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
8const iterare_1 = require("iterare");
9const os_1 = require("os");
10const pathToRegexp = require("path-to-regexp");
11const application_config_1 = require("./application-config");
12const constants_1 = require("./constants");
13const optional_require_1 = require("./helpers/optional-require");
14const container_1 = require("./middleware/container");
15const middleware_module_1 = require("./middleware/middleware-module");
16const nest_application_context_1 = require("./nest-application-context");
17const routes_resolver_1 = require("./router/routes-resolver");
18const { SocketModule } = optional_require_1.optionalRequire('@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'));
19const { MicroservicesModule } = optional_require_1.optionalRequire('@nestjs/microservices/microservices-module', () => require('@nestjs/microservices/microservices-module'));
20/**
21 * @publicApi
22 */
23class NestApplication extends nest_application_context_1.NestApplicationContext {
24 constructor(container, httpAdapter, config, appOptions = {}) {
25 super(container);
26 this.httpAdapter = httpAdapter;
27 this.config = config;
28 this.appOptions = appOptions;
29 this.logger = new logger_service_1.Logger(NestApplication.name, {
30 timestamp: true,
31 });
32 this.middlewareModule = new middleware_module_1.MiddlewareModule();
33 this.middlewareContainer = new container_1.MiddlewareContainer(this.container);
34 this.microservicesModule = MicroservicesModule && new MicroservicesModule();
35 this.socketModule = SocketModule && new SocketModule();
36 this.microservices = [];
37 this.isListening = false;
38 this.selectContextModule();
39 this.registerHttpServer();
40 this.routesResolver = new routes_resolver_1.RoutesResolver(this.container, this.config, this.injector);
41 }
42 async dispose() {
43 this.socketModule && (await this.socketModule.close());
44 this.microservicesModule && (await this.microservicesModule.close());
45 this.httpAdapter && (await this.httpAdapter.close());
46 await Promise.all(iterare_1.iterate(this.microservices).map(async (microservice) => {
47 microservice.setIsTerminated(true);
48 await microservice.close();
49 }));
50 }
51 getHttpAdapter() {
52 return this.httpAdapter;
53 }
54 registerHttpServer() {
55 this.httpServer = this.createServer();
56 }
57 getUnderlyingHttpServer() {
58 return this.httpAdapter.getHttpServer();
59 }
60 applyOptions() {
61 if (!this.appOptions || !this.appOptions.cors) {
62 return undefined;
63 }
64 const passCustomOptions = shared_utils_1.isObject(this.appOptions.cors) || shared_utils_1.isFunction(this.appOptions.cors);
65 if (!passCustomOptions) {
66 return this.enableCors();
67 }
68 return this.enableCors(this.appOptions.cors);
69 }
70 createServer() {
71 this.httpAdapter.initHttpServer(this.appOptions);
72 return this.httpAdapter.getHttpServer();
73 }
74 async registerModules() {
75 this.registerWsModule();
76 if (this.microservicesModule) {
77 this.microservicesModule.register(this.container, this.config);
78 this.microservicesModule.setupClients(this.container);
79 }
80 await this.middlewareModule.register(this.middlewareContainer, this.container, this.config, this.injector, this.httpAdapter);
81 }
82 registerWsModule() {
83 if (!this.socketModule) {
84 return;
85 }
86 this.socketModule.register(this.container, this.config, this.httpServer);
87 }
88 async init() {
89 var _a;
90 this.applyOptions();
91 await ((_a = this.httpAdapter) === null || _a === void 0 ? void 0 : _a.init());
92 const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false;
93 useBodyParser && this.registerParserMiddleware();
94 await this.registerModules();
95 await this.registerRouter();
96 await this.callInitHook();
97 await this.registerRouterHooks();
98 await this.callBootstrapHook();
99 this.isInitialized = true;
100 this.logger.log(constants_1.MESSAGES.APPLICATION_READY);
101 return this;
102 }
103 registerParserMiddleware() {
104 this.httpAdapter.registerParserMiddleware();
105 }
106 async registerRouter() {
107 await this.registerMiddleware(this.httpAdapter);
108 const prefix = this.config.getGlobalPrefix();
109 const basePath = shared_utils_1.addLeadingSlash(prefix);
110 this.routesResolver.resolve(this.httpAdapter, basePath);
111 }
112 async registerRouterHooks() {
113 this.routesResolver.registerNotFoundHandler();
114 this.routesResolver.registerExceptionHandler();
115 }
116 connectMicroservice(microserviceOptions, hybridAppOptions = {}) {
117 const { NestMicroservice } = load_package_util_1.loadPackage('@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'));
118 const { inheritAppConfig } = hybridAppOptions;
119 const applicationConfig = inheritAppConfig
120 ? this.config
121 : new application_config_1.ApplicationConfig();
122 const instance = new NestMicroservice(this.container, microserviceOptions, applicationConfig);
123 instance.registerListeners();
124 instance.setIsInitialized(true);
125 instance.setIsInitHookCalled(true);
126 this.microservices.push(instance);
127 return instance;
128 }
129 getMicroservices() {
130 return this.microservices;
131 }
132 getHttpServer() {
133 return this.httpServer;
134 }
135 async startAllMicroservices() {
136 await Promise.all(this.microservices.map(msvc => msvc.listen()));
137 return this;
138 }
139 startAllMicroservicesAsync() {
140 this.logger.warn('DEPRECATED! "startAllMicroservicesAsync" method is deprecated and will be removed in the next major release. Please, use "startAllMicroservices" instead.');
141 return this.startAllMicroservices();
142 }
143 use(...args) {
144 this.httpAdapter.use(...args);
145 return this;
146 }
147 enableCors(options) {
148 this.httpAdapter.enableCors(options);
149 }
150 enableVersioning(options = { type: common_1.VersioningType.URI }) {
151 this.config.enableVersioning(options);
152 return this;
153 }
154 async listen(port, ...args) {
155 !this.isInitialized && (await this.init());
156 return new Promise((resolve, reject) => {
157 const errorHandler = (e) => {
158 var _a;
159 this.logger.error((_a = e === null || e === void 0 ? void 0 : e.toString) === null || _a === void 0 ? void 0 : _a.call(e));
160 reject(e);
161 };
162 this.httpServer.once('error', errorHandler);
163 const isCallbackInOriginalArgs = shared_utils_1.isFunction(args[args.length - 1]);
164 const listenFnArgs = isCallbackInOriginalArgs
165 ? args.slice(0, args.length - 1)
166 : args;
167 this.httpAdapter.listen(port, ...listenFnArgs, (...originalCallbackArgs) => {
168 var _a, _b;
169 if ((_b = (_a = this.appOptions) === null || _a === void 0 ? void 0 : _a.autoFlushLogs) !== null && _b !== void 0 ? _b : true) {
170 this.flushLogs();
171 }
172 if (originalCallbackArgs[0] instanceof Error) {
173 return reject(originalCallbackArgs[0]);
174 }
175 const address = this.httpServer.address();
176 if (address) {
177 this.httpServer.removeListener('error', errorHandler);
178 this.isListening = true;
179 resolve(this.httpServer);
180 }
181 if (isCallbackInOriginalArgs) {
182 args[args.length - 1](...originalCallbackArgs);
183 }
184 });
185 });
186 }
187 listenAsync(port, ...args) {
188 this.logger.warn('DEPRECATED! "listenAsync" method is deprecated and will be removed in the next major release. Please, use "listen" instead.');
189 return this.listen(port, ...args);
190 }
191 async getUrl() {
192 return new Promise((resolve, reject) => {
193 if (!this.isListening) {
194 this.logger.error(constants_1.MESSAGES.CALL_LISTEN_FIRST);
195 reject(constants_1.MESSAGES.CALL_LISTEN_FIRST);
196 }
197 const address = this.httpServer.address();
198 resolve(this.formatAddress(address));
199 });
200 }
201 formatAddress(address) {
202 if (shared_utils_1.isString(address)) {
203 if (os_1.platform() === 'win32') {
204 return address;
205 }
206 const basePath = encodeURIComponent(address);
207 return `${this.getProtocol()}+unix://${basePath}`;
208 }
209 let host = this.host();
210 if (address && address.family === 'IPv6') {
211 if (host === '::') {
212 host = '[::1]';
213 }
214 else {
215 host = `[${host}]`;
216 }
217 }
218 else if (host === '0.0.0.0') {
219 host = '127.0.0.1';
220 }
221 return `${this.getProtocol()}://${host}:${address.port}`;
222 }
223 setGlobalPrefix(prefix, options) {
224 this.config.setGlobalPrefix(prefix);
225 if (options) {
226 const exclude = options === null || options === void 0 ? void 0 : options.exclude.map((route) => {
227 if (shared_utils_1.isString(route)) {
228 return {
229 requestMethod: common_1.RequestMethod.ALL,
230 pathRegex: pathToRegexp(shared_utils_1.addLeadingSlash(route)),
231 };
232 }
233 return {
234 requestMethod: route.method,
235 pathRegex: pathToRegexp(shared_utils_1.addLeadingSlash(route.path)),
236 };
237 });
238 this.config.setGlobalPrefixOptions(Object.assign(Object.assign({}, options), { exclude }));
239 }
240 return this;
241 }
242 useWebSocketAdapter(adapter) {
243 this.config.setIoAdapter(adapter);
244 return this;
245 }
246 useGlobalFilters(...filters) {
247 this.config.useGlobalFilters(...filters);
248 return this;
249 }
250 useGlobalPipes(...pipes) {
251 this.config.useGlobalPipes(...pipes);
252 return this;
253 }
254 useGlobalInterceptors(...interceptors) {
255 this.config.useGlobalInterceptors(...interceptors);
256 return this;
257 }
258 useGlobalGuards(...guards) {
259 this.config.useGlobalGuards(...guards);
260 return this;
261 }
262 useStaticAssets(pathOrOptions, options) {
263 this.httpAdapter.useStaticAssets &&
264 this.httpAdapter.useStaticAssets(pathOrOptions, options);
265 return this;
266 }
267 setBaseViewsDir(path) {
268 this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path);
269 return this;
270 }
271 setViewEngine(engineOrOptions) {
272 this.httpAdapter.setViewEngine &&
273 this.httpAdapter.setViewEngine(engineOrOptions);
274 return this;
275 }
276 host() {
277 const address = this.httpServer.address();
278 if (shared_utils_1.isString(address)) {
279 return undefined;
280 }
281 return address && address.address;
282 }
283 getProtocol() {
284 return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
285 }
286 async registerMiddleware(instance) {
287 await this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
288 }
289}
290exports.NestApplication = NestApplication;