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