Spaces:
Sleeping
Sleeping
File size: 13,782 Bytes
cfbbc1a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestApplication = void 0;
const common_1 = require("@nestjs/common");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const iterare_1 = require("iterare");
const os_1 = require("os");
const application_config_1 = require("./application-config");
const constants_1 = require("./constants");
const optional_require_1 = require("./helpers/optional-require");
const injector_1 = require("./injector/injector");
const container_1 = require("./middleware/container");
const middleware_module_1 = require("./middleware/middleware-module");
const utils_1 = require("./middleware/utils");
const nest_application_context_1 = require("./nest-application-context");
const routes_resolver_1 = require("./router/routes-resolver");
const { SocketModule } = (0, optional_require_1.optionalRequire)('@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'));
const { MicroservicesModule } = (0, optional_require_1.optionalRequire)('@nestjs/microservices/microservices-module', () => require('@nestjs/microservices/microservices-module'));
/**
* @publicApi
*/
class NestApplication extends nest_application_context_1.NestApplicationContext {
constructor(container, httpAdapter, config, graphInspector, appOptions = {}) {
super(container, appOptions);
this.httpAdapter = httpAdapter;
this.config = config;
this.graphInspector = graphInspector;
this.logger = new logger_service_1.Logger(NestApplication.name, {
timestamp: true,
});
this.middlewareContainer = new container_1.MiddlewareContainer(this.container);
this.microservicesModule = MicroservicesModule && new MicroservicesModule();
this.socketModule = SocketModule && new SocketModule();
this.microservices = [];
this.isListening = false;
this.isWsModuleRegistered = false;
this.selectContextModule();
this.registerHttpServer();
this.injector = new injector_1.Injector({
preview: this.appOptions.preview,
instanceDecorator: appOptions.instrument?.instanceDecorator,
});
this.middlewareModule = new middleware_module_1.MiddlewareModule();
this.routesResolver = new routes_resolver_1.RoutesResolver(this.container, this.config, this.injector, this.graphInspector);
}
async dispose() {
this.socketModule && (await this.socketModule.close());
this.microservicesModule && (await this.microservicesModule.close());
this.httpAdapter && (await this.httpAdapter.close());
await Promise.all((0, iterare_1.iterate)(this.microservices).map(async (microservice) => {
microservice.setIsTerminated(true);
await microservice.close();
}));
}
getHttpAdapter() {
return this.httpAdapter;
}
registerHttpServer() {
this.httpServer = this.createServer();
}
getUnderlyingHttpServer() {
return this.httpAdapter.getHttpServer();
}
applyOptions() {
if (!this.appOptions || !this.appOptions.cors) {
return undefined;
}
const passCustomOptions = (0, shared_utils_1.isObject)(this.appOptions.cors) || (0, shared_utils_1.isFunction)(this.appOptions.cors);
if (!passCustomOptions) {
return this.enableCors();
}
return this.enableCors(this.appOptions.cors);
}
createServer() {
this.httpAdapter.initHttpServer(this.appOptions);
return this.httpAdapter.getHttpServer();
}
async registerModules() {
this.registerWsModule();
if (this.microservicesModule) {
this.microservicesModule.register(this.container, this.graphInspector, this.config, this.appOptions);
this.microservicesModule.setupClients(this.container);
}
await this.middlewareModule.register(this.middlewareContainer, this.container, this.config, this.injector, this.httpAdapter, this.graphInspector, this.appOptions);
}
registerWsModule() {
if (!this.socketModule) {
return;
}
this.socketModule.register(this.container, this.config, this.graphInspector, this.appOptions, this.httpServer);
this.isWsModuleRegistered = true;
}
async init() {
if (this.isInitialized) {
return this;
}
this.applyOptions();
await this.httpAdapter?.init?.();
const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false;
useBodyParser && this.registerParserMiddleware();
await this.registerModules();
await this.registerRouter();
await this.callInitHook();
await this.registerRouterHooks();
await this.callBootstrapHook();
this.isInitialized = true;
this.logger.log(constants_1.MESSAGES.APPLICATION_READY);
return this;
}
registerParserMiddleware() {
const prefix = this.config.getGlobalPrefix();
const rawBody = !!this.appOptions?.rawBody;
this.httpAdapter.registerParserMiddleware(prefix, rawBody);
}
async registerRouter() {
await this.registerMiddleware(this.httpAdapter);
const prefix = this.config.getGlobalPrefix();
const basePath = (0, shared_utils_1.addLeadingSlash)(prefix);
this.routesResolver.resolve(this.httpAdapter, basePath);
}
async registerRouterHooks() {
this.routesResolver.registerNotFoundHandler();
this.routesResolver.registerExceptionHandler();
}
connectMicroservice(microserviceOptions, hybridAppOptions = {}) {
const { NestMicroservice } = (0, load_package_util_1.loadPackage)('@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'));
const { inheritAppConfig } = hybridAppOptions;
const applicationConfig = inheritAppConfig
? this.config
: new application_config_1.ApplicationConfig();
const instance = new NestMicroservice(this.container, microserviceOptions, this.graphInspector, applicationConfig);
if (!hybridAppOptions.deferInitialization) {
instance.registerListeners();
instance.setIsInitialized(true);
instance.setIsInitHookCalled(true);
}
this.microservices.push(instance);
return instance;
}
getMicroservices() {
return this.microservices;
}
getHttpServer() {
return this.httpServer;
}
async startAllMicroservices() {
this.assertNotInPreviewMode('startAllMicroservices');
await Promise.all(this.microservices.map(msvc => msvc.listen()));
return this;
}
use(...args) {
this.httpAdapter.use(...args);
return this;
}
useBodyParser(...args) {
if (!('useBodyParser' in this.httpAdapter)) {
this.logger.warn('Your HTTP Adapter does not support `.useBodyParser`.');
return this;
}
const [parserType, ...otherArgs] = args;
const rawBody = !!this.appOptions.rawBody;
this.httpAdapter.useBodyParser?.(...[parserType, rawBody, ...otherArgs]);
return this;
}
enableCors(options) {
this.httpAdapter.enableCors(options);
}
enableVersioning(options = { type: common_1.VersioningType.URI }) {
this.config.enableVersioning(options);
return this;
}
async listen(port, ...args) {
this.assertNotInPreviewMode('listen');
if (!this.isInitialized) {
await this.init();
}
const httpAdapterHost = this.container.getHttpAdapterHostRef();
return new Promise((resolve, reject) => {
const errorHandler = (e) => {
this.logger.error(e?.toString?.());
reject(e);
};
this.httpServer.once('error', errorHandler);
const isCallbackInOriginalArgs = (0, shared_utils_1.isFunction)(args[args.length - 1]);
const listenFnArgs = isCallbackInOriginalArgs
? args.slice(0, args.length - 1)
: args;
this.httpAdapter.listen(port, ...listenFnArgs, (...originalCallbackArgs) => {
if (this.appOptions?.autoFlushLogs ?? true) {
this.flushLogs();
}
if (originalCallbackArgs[0] instanceof Error) {
return reject(originalCallbackArgs[0]);
}
const address = this.httpServer.address();
if (address) {
this.httpServer.removeListener('error', errorHandler);
this.isListening = true;
httpAdapterHost.listening = true;
resolve(this.httpServer);
}
if (isCallbackInOriginalArgs) {
args[args.length - 1](...originalCallbackArgs);
}
});
});
}
async getUrl() {
return new Promise((resolve, reject) => {
if (!this.isListening) {
this.logger.error(constants_1.MESSAGES.CALL_LISTEN_FIRST);
reject(constants_1.MESSAGES.CALL_LISTEN_FIRST);
return;
}
const address = this.httpServer.address();
resolve(this.formatAddress(address));
});
}
formatAddress(address) {
if ((0, shared_utils_1.isString)(address)) {
if ((0, os_1.platform)() === 'win32') {
return address;
}
const basePath = encodeURIComponent(address);
return `${this.getProtocol()}+unix://${basePath}`;
}
let host = this.host();
if (address && address.family === 'IPv6') {
if (host === '::') {
host = '[::1]';
}
else {
host = `[${host}]`;
}
}
else if (host === '0.0.0.0') {
host = '127.0.0.1';
}
return `${this.getProtocol()}://${host}:${address.port}`;
}
setGlobalPrefix(prefix, options) {
this.config.setGlobalPrefix(prefix);
if (options) {
const exclude = options?.exclude
? (0, utils_1.mapToExcludeRoute)(options.exclude)
: [];
this.config.setGlobalPrefixOptions({
...options,
exclude,
});
}
return this;
}
useWebSocketAdapter(adapter) {
if (this.isWsModuleRegistered) {
this.logger.warn('useWebSocketAdapter() was called after WebSocket gateways were already initialized. The provided adapter will be stored but will NOT be applied to existing gateways — they remain bound to the previously installed adapter. To install a custom adapter, call app.useWebSocketAdapter(...) BEFORE app.init() (or app.listen()).');
}
this.config.setIoAdapter(adapter);
return this;
}
useGlobalFilters(...filters) {
filters = this.applyInstanceDecoratorIfRegistered(...filters);
this.config.useGlobalFilters(...filters);
filters.forEach(item => this.graphInspector.insertOrphanedEnhancer({
subtype: 'filter',
ref: item,
}));
return this;
}
useGlobalPipes(...pipes) {
pipes = this.applyInstanceDecoratorIfRegistered(...pipes);
this.config.useGlobalPipes(...pipes);
pipes.forEach(item => this.graphInspector.insertOrphanedEnhancer({
subtype: 'pipe',
ref: item,
}));
return this;
}
useGlobalInterceptors(...interceptors) {
interceptors = this.applyInstanceDecoratorIfRegistered(...interceptors);
this.config.useGlobalInterceptors(...interceptors);
interceptors.forEach(item => this.graphInspector.insertOrphanedEnhancer({
subtype: 'interceptor',
ref: item,
}));
return this;
}
useGlobalGuards(...guards) {
guards = this.applyInstanceDecoratorIfRegistered(...guards);
this.config.useGlobalGuards(...guards);
guards.forEach(item => this.graphInspector.insertOrphanedEnhancer({
subtype: 'guard',
ref: item,
}));
return this;
}
useStaticAssets(pathOrOptions, options) {
this.httpAdapter.useStaticAssets &&
this.httpAdapter.useStaticAssets(pathOrOptions, options);
return this;
}
setBaseViewsDir(path) {
this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path);
return this;
}
setViewEngine(engineOrOptions) {
this.httpAdapter.setViewEngine &&
this.httpAdapter.setViewEngine(engineOrOptions);
return this;
}
host() {
const address = this.httpServer.address();
if ((0, shared_utils_1.isString)(address)) {
return undefined;
}
return address && address.address;
}
getProtocol() {
return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
}
async registerMiddleware(instance) {
await this.middlewareModule.registerMiddleware(this.middlewareContainer, instance);
}
applyInstanceDecoratorIfRegistered(...instances) {
if (this.appOptions.instrument?.instanceDecorator) {
return instances.map(instance => this.appOptions.instrument.instanceDecorator(instance));
}
return instances;
}
}
exports.NestApplication = NestApplication;
|