UNPKG

11.7 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 } = (0, optional_require_1.optionalRequire)('@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'));
19const { MicroservicesModule } = (0, 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((0, 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 = (0, shared_utils_1.isObject)(this.appOptions.cors) || (0, 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 var _a;
105 const prefix = this.config.getGlobalPrefix();
106 const rawBody = !!((_a = this.appOptions) === null || _a === void 0 ? void 0 : _a.rawBody);
107 this.httpAdapter.registerParserMiddleware(prefix, rawBody);
108 }
109 async registerRouter() {
110 await this.registerMiddleware(this.httpAdapter);
111 const prefix = this.config.getGlobalPrefix();
112 const basePath = (0, shared_utils_1.addLeadingSlash)(prefix);
113 this.routesResolver.resolve(this.httpAdapter, basePath);
114 }
115 async registerRouterHooks() {
116 this.routesResolver.registerNotFoundHandler();
117 this.routesResolver.registerExceptionHandler();
118 }
119 connectMicroservice(microserviceOptions, hybridAppOptions = {}) {
120 const { NestMicroservice } = (0, load_package_util_1.loadPackage)('@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'));
121 const { inheritAppConfig } = hybridAppOptions;
122 const applicationConfig = inheritAppConfig
123 ? this.config
124 : new application_config_1.ApplicationConfig();
125 const instance = new NestMicroservice(this.container, microserviceOptions, applicationConfig);
126 instance.registerListeners();
127 instance.setIsInitialized(true);
128 instance.setIsInitHookCalled(true);
129 this.microservices.push(instance);
130 return instance;
131 }
132 getMicroservices() {
133 return this.microservices;
134 }
135 getHttpServer() {
136 return this.httpServer;
137 }
138 async startAllMicroservices() {
139 await Promise.all(this.microservices.map(msvc => msvc.listen()));
140 return this;
141 }
142 use(...args) {
143 this.httpAdapter.use(...args);
144 return this;
145 }
146 enableCors(options) {
147 this.httpAdapter.enableCors(options);
148 }
149 enableVersioning(options = { type: common_1.VersioningType.URI }) {
150 this.config.enableVersioning(options);
151 return this;
152 }
153 async listen(port, ...args) {
154 !this.isInitialized && (await this.init());
155 return new Promise((resolve, reject) => {
156 const errorHandler = (e) => {
157 var _a;
158 this.logger.error((_a = e === null || e === void 0 ? void 0 : e.toString) === null || _a === void 0 ? void 0 : _a.call(e));
159 reject(e);
160 };
161 this.httpServer.once('error', errorHandler);
162 const isCallbackInOriginalArgs = (0, shared_utils_1.isFunction)(args[args.length - 1]);
163 const listenFnArgs = isCallbackInOriginalArgs
164 ? args.slice(0, args.length - 1)
165 : args;
166 this.httpAdapter.listen(port, ...listenFnArgs, (...originalCallbackArgs) => {
167 var _a, _b;
168 if ((_b = (_a = this.appOptions) === null || _a === void 0 ? void 0 : _a.autoFlushLogs) !== null && _b !== void 0 ? _b : true) {
169 this.flushLogs();
170 }
171 if (originalCallbackArgs[0] instanceof Error) {
172 return reject(originalCallbackArgs[0]);
173 }
174 const address = this.httpServer.address();
175 if (address) {
176 this.httpServer.removeListener('error', errorHandler);
177 this.isListening = true;
178 resolve(this.httpServer);
179 }
180 if (isCallbackInOriginalArgs) {
181 args[args.length - 1](...originalCallbackArgs);
182 }
183 });
184 });
185 }
186 async getUrl() {
187 return new Promise((resolve, reject) => {
188 if (!this.isListening) {
189 this.logger.error(constants_1.MESSAGES.CALL_LISTEN_FIRST);
190 reject(constants_1.MESSAGES.CALL_LISTEN_FIRST);
191 }
192 const address = this.httpServer.address();
193 resolve(this.formatAddress(address));
194 });
195 }
196 formatAddress(address) {
197 if ((0, shared_utils_1.isString)(address)) {
198 if ((0, os_1.platform)() === 'win32') {
199 return address;
200 }
201 const basePath = encodeURIComponent(address);
202 return `${this.getProtocol()}+unix://${basePath}`;
203 }
204 let host = this.host();
205 if (address && address.family === 'IPv6') {
206 if (host === '::') {
207 host = '[::1]';
208 }
209 else {
210 host = `[${host}]`;
211 }
212 }
213 else if (host === '0.0.0.0') {
214 host = '127.0.0.1';
215 }
216 return `${this.getProtocol()}://${host}:${address.port}`;
217 }
218 setGlobalPrefix(prefix, options) {
219 this.config.setGlobalPrefix(prefix);
220 if (options) {
221 const exclude = options === null || options === void 0 ? void 0 : options.exclude.map((route) => {
222 if ((0, shared_utils_1.isString)(route)) {
223 return {
224 requestMethod: common_1.RequestMethod.ALL,
225 pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route)),
226 };
227 }
228 return {
229 requestMethod: route.method,
230 pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route.path)),
231 };
232 });
233 this.config.setGlobalPrefixOptions(Object.assign(Object.assign({}, options), { exclude }));
234 }
235 return this;
236 }
237 useWebSocketAdapter(adapter) {
238 this.config.setIoAdapter(adapter);
239 return this;
240 }
241 useGlobalFilters(...filters) {
242 this.config.useGlobalFilters(...filters);
243 return this;
244 }
245 useGlobalPipes(...pipes) {
246 this.config.useGlobalPipes(...pipes);
247 return this;
248 }
249 useGlobalInterceptors(...interceptors) {
250 this.config.useGlobalInterceptors(...interceptors);
251 return this;
252 }
253 useGlobalGuards(...guards) {
254 this.config.useGlobalGuards(...guards);
255 return this;
256 }
257 useStaticAssets(pathOrOptions, options) {
258 this.httpAdapter.useStaticAssets &&
259 this.httpAdapter.useStaticAssets(pathOrOptions, options);
260 return this;
261 }
262 setBaseViewsDir(path) {
263 this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path);
264 return this;
265 }
266 setViewEngine(engineOrOptions) {
267 this.httpAdapter.setViewEngine &&
268 this.httpAdapter.setViewEngine(engineOrOptions);
269 return this;
270 }
271 host() {
272 const address = this.httpServer.address();
273 if ((0, shared_utils_1.isString)(address)) {
274 return undefined;
275 }
276 return address && address.address;
277 }
278 getProtocol() {
279 return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
280 }
281 async registerMiddleware(instance) {
282 await this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
283 }
284}
285exports.NestApplication = NestApplication;