UNPKG

8.82 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.NestFactory = exports.NestFactoryStatic = void 0;
4const logger_service_1 = require("@nestjs/common/services/logger.service");
5const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
6const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
7const application_config_1 = require("./application-config");
8const constants_1 = require("./constants");
9const exceptions_zone_1 = require("./errors/exceptions-zone");
10const load_adapter_1 = require("./helpers/load-adapter");
11const rethrow_1 = require("./helpers/rethrow");
12const container_1 = require("./injector/container");
13const instance_loader_1 = require("./injector/instance-loader");
14const metadata_scanner_1 = require("./metadata-scanner");
15const nest_application_1 = require("./nest-application");
16const nest_application_context_1 = require("./nest-application-context");
17const scanner_1 = require("./scanner");
18/**
19 * @publicApi
20 */
21class NestFactoryStatic {
22 constructor() {
23 this.logger = new logger_service_1.Logger('NestFactory', {
24 timestamp: true,
25 });
26 this.abortOnError = true;
27 this.autoFlushLogs = false;
28 }
29 async create(module, serverOrOptions, options) {
30 const [httpServer, appOptions] = this.isHttpServer(serverOrOptions)
31 ? [serverOrOptions, options]
32 : [this.createHttpAdapter(), serverOrOptions];
33 const applicationConfig = new application_config_1.ApplicationConfig();
34 const container = new container_1.NestContainer(applicationConfig);
35 this.setAbortOnError(serverOrOptions, options);
36 this.registerLoggerConfiguration(appOptions);
37 await this.initialize(module, container, applicationConfig, httpServer);
38 const instance = new nest_application_1.NestApplication(container, httpServer, applicationConfig, appOptions);
39 const target = this.createNestInstance(instance);
40 return this.createAdapterProxy(target, httpServer);
41 }
42 /**
43 * Creates an instance of NestMicroservice.
44 *
45 * @param module Entry (root) application module class
46 * @param options Optional microservice configuration
47 *
48 * @returns A promise that, when resolved,
49 * contains a reference to the NestMicroservice instance.
50 */
51 async createMicroservice(module, options) {
52 const { NestMicroservice } = (0, load_package_util_1.loadPackage)('@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'));
53 const applicationConfig = new application_config_1.ApplicationConfig();
54 const container = new container_1.NestContainer(applicationConfig);
55 this.setAbortOnError(options);
56 this.registerLoggerConfiguration(options);
57 await this.initialize(module, container, applicationConfig);
58 return this.createNestInstance(new NestMicroservice(container, options, applicationConfig));
59 }
60 /**
61 * Creates an instance of NestApplicationContext.
62 *
63 * @param module Entry (root) application module class
64 * @param options Optional Nest application configuration
65 *
66 * @returns A promise that, when resolved,
67 * contains a reference to the NestApplicationContext instance.
68 */
69 async createApplicationContext(module, options) {
70 const container = new container_1.NestContainer();
71 this.setAbortOnError(options);
72 this.registerLoggerConfiguration(options);
73 await this.initialize(module, container);
74 const modules = container.getModules().values();
75 const root = modules.next().value;
76 const context = this.createNestInstance(new nest_application_context_1.NestApplicationContext(container, [], root));
77 if (this.autoFlushLogs) {
78 context.flushLogsOnOverride();
79 }
80 return context.init();
81 }
82 createNestInstance(instance) {
83 return this.createProxy(instance);
84 }
85 async initialize(module, container, config = new application_config_1.ApplicationConfig(), httpServer = null) {
86 const instanceLoader = new instance_loader_1.InstanceLoader(container);
87 const metadataScanner = new metadata_scanner_1.MetadataScanner();
88 const dependenciesScanner = new scanner_1.DependenciesScanner(container, metadataScanner, config);
89 container.setHttpAdapter(httpServer);
90 const teardown = this.abortOnError === false ? rethrow_1.rethrow : undefined;
91 await (httpServer === null || httpServer === void 0 ? void 0 : httpServer.init());
92 try {
93 this.logger.log(constants_1.MESSAGES.APPLICATION_START);
94 await exceptions_zone_1.ExceptionsZone.asyncRun(async () => {
95 await dependenciesScanner.scan(module);
96 await instanceLoader.createInstancesOfDependencies();
97 dependenciesScanner.applyApplicationProviders();
98 }, teardown, this.autoFlushLogs);
99 }
100 catch (e) {
101 this.handleInitializationError(e);
102 }
103 }
104 handleInitializationError(err) {
105 if (this.abortOnError) {
106 process.abort();
107 }
108 (0, rethrow_1.rethrow)(err);
109 }
110 createProxy(target) {
111 const proxy = this.createExceptionProxy();
112 return new Proxy(target, {
113 get: proxy,
114 set: proxy,
115 });
116 }
117 createExceptionProxy() {
118 return (receiver, prop) => {
119 if (!(prop in receiver)) {
120 return;
121 }
122 if ((0, shared_utils_1.isFunction)(receiver[prop])) {
123 return this.createExceptionZone(receiver, prop);
124 }
125 return receiver[prop];
126 };
127 }
128 createExceptionZone(receiver, prop) {
129 const teardown = this.abortOnError === false ? rethrow_1.rethrow : undefined;
130 return (...args) => {
131 let result;
132 exceptions_zone_1.ExceptionsZone.run(() => {
133 result = receiver[prop](...args);
134 }, teardown);
135 return result;
136 };
137 }
138 registerLoggerConfiguration(options) {
139 if (!options) {
140 return;
141 }
142 const { logger, bufferLogs, autoFlushLogs } = options;
143 if (logger !== true && !(0, shared_utils_1.isNil)(logger)) {
144 logger_service_1.Logger.overrideLogger(logger);
145 }
146 if (bufferLogs) {
147 logger_service_1.Logger.attachBuffer();
148 }
149 this.autoFlushLogs = autoFlushLogs !== null && autoFlushLogs !== void 0 ? autoFlushLogs : true;
150 }
151 createHttpAdapter(httpServer) {
152 const { ExpressAdapter } = (0, load_adapter_1.loadAdapter)('@nestjs/platform-express', 'HTTP', () => require('@nestjs/platform-express'));
153 return new ExpressAdapter(httpServer);
154 }
155 isHttpServer(serverOrOptions) {
156 return !!(serverOrOptions && serverOrOptions.patch);
157 }
158 setAbortOnError(serverOrOptions, options) {
159 this.abortOnError = this.isHttpServer(serverOrOptions)
160 ? !(options && options.abortOnError === false)
161 : !(serverOrOptions && serverOrOptions.abortOnError === false);
162 }
163 createAdapterProxy(app, adapter) {
164 const proxy = new Proxy(app, {
165 get: (receiver, prop) => {
166 const mapToProxy = (result) => {
167 return result instanceof Promise
168 ? result.then(mapToProxy)
169 : result instanceof nest_application_1.NestApplication
170 ? proxy
171 : result;
172 };
173 if (!(prop in receiver) && prop in adapter) {
174 return (...args) => {
175 const result = this.createExceptionZone(adapter, prop)(...args);
176 return mapToProxy(result);
177 };
178 }
179 if ((0, shared_utils_1.isFunction)(receiver[prop])) {
180 return (...args) => {
181 const result = receiver[prop](...args);
182 return mapToProxy(result);
183 };
184 }
185 return receiver[prop];
186 },
187 });
188 return proxy;
189 }
190}
191exports.NestFactoryStatic = NestFactoryStatic;
192/**
193 * Use NestFactory to create an application instance.
194 *
195 * ### Specifying an entry module
196 *
197 * Pass the required *root module* for the application via the module parameter.
198 * By convention, it is usually called `ApplicationModule`. Starting with this
199 * module, Nest assembles the dependency graph and begins the process of
200 * Dependency Injection and instantiates the classes needed to launch your
201 * application.
202 *
203 * @publicApi
204 */
205exports.NestFactory = new NestFactoryStatic();