UNPKG

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