Spaces:
Sleeping
Sleeping
File size: 12,771 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 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NestApplicationContext = void 0;
const common_1 = require("@nestjs/common");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const iterare_1 = require("iterare");
const constants_1 = require("./constants");
const exceptions_1 = require("./errors/exceptions");
const context_id_factory_1 = require("./helpers/context-id-factory");
const hooks_1 = require("./hooks");
const abstract_instance_resolver_1 = require("./injector/abstract-instance-resolver");
const injector_1 = require("./injector/injector");
const instance_links_host_1 = require("./injector/instance-links-host");
/**
* @publicApi
*/
class NestApplicationContext extends abstract_instance_resolver_1.AbstractInstanceResolver {
get instanceLinksHost() {
if (!this._instanceLinksHost) {
this._instanceLinksHost = new instance_links_host_1.InstanceLinksHost(this.container);
}
return this._instanceLinksHost;
}
constructor(container, appOptions = {}, contextModule = null, scope = new Array()) {
super();
this.container = container;
this.appOptions = appOptions;
this.contextModule = contextModule;
this.scope = scope;
this.isInitialized = false;
this.logger = new common_1.Logger(NestApplicationContext.name, {
timestamp: true,
});
this.shouldFlushLogsOnOverride = false;
this.activeShutdownSignals = new Array();
this.injector = new injector_1.Injector();
this.moduleCompiler = container.getModuleCompiler();
if (this.appOptions.preview) {
this.printInPreviewModeWarning();
}
}
selectContextModule() {
const modules = this.container.getModules().values();
this.contextModule = modules.next().value;
}
/**
* Allows navigating through the modules tree, for example, to pull out a specific instance from the selected module.
* @returns {INestApplicationContext}
*/
select(moduleType, selectOptions) {
const modulesContainer = this.container.getModules();
const contextModuleCtor = this.contextModule.metatype;
const scope = this.scope.concat(contextModuleCtor);
const moduleTokenFactory = this.container.getModuleTokenFactory();
const { type, dynamicMetadata } = this.moduleCompiler.extractMetadata(moduleType);
const token = dynamicMetadata
? moduleTokenFactory.createForDynamic(type, dynamicMetadata, moduleType)
: moduleTokenFactory.createForStatic(type, moduleType);
const selectedModule = modulesContainer.get(token);
if (!selectedModule) {
throw new exceptions_1.UnknownModuleException(type.name);
}
const options = typeof selectOptions?.abortOnError !== 'undefined'
? {
...this.appOptions,
...selectOptions,
}
: this.appOptions;
return new NestApplicationContext(this.container, options, selectedModule, scope);
}
/**
* Retrieves an instance (or a list of instances) of either injectable or controller, otherwise, throws exception.
* @returns {TResult | Array<TResult>}
*/
get(typeOrToken, options = { strict: false }) {
return !(options && options.strict)
? this.find(typeOrToken, options)
: this.find(typeOrToken, {
moduleId: this.contextModule?.id,
each: options.each,
});
}
/**
* Resolves transient or request-scoped instance (or a list of instances) of either injectable or controller, otherwise, throws exception.
* @returns {Promise<TResult | Array<TResult>>}
*/
resolve(typeOrToken, contextId = (0, context_id_factory_1.createContextId)(), options = { strict: false }) {
return this.resolvePerContext(typeOrToken, this.contextModule, contextId, options);
}
/**
* Registers the request/context object for a given context ID (DI container sub-tree).
* @returns {void}
*/
registerRequestByContextId(request, contextId) {
this.container.registerRequestProvider(request, contextId);
}
/**
* Initializes the Nest application.
* Calls the Nest lifecycle events.
*
* @returns {Promise<this>} The NestApplicationContext instance as Promise
*/
async init() {
if (this.isInitialized) {
return this;
}
/* eslint-disable-next-line no-async-promise-executor */
this.initializationPromise = new Promise(async (resolve, reject) => {
try {
await this.callInitHook();
await this.callBootstrapHook();
resolve();
}
catch (err) {
reject(err);
}
});
await this.initializationPromise;
this.isInitialized = true;
return this;
}
/**
* Terminates the application
* @returns {Promise<void>}
*/
async close(signal) {
await this.initializationPromise;
await this.callDestroyHook();
await this.callBeforeShutdownHook(signal);
await this.dispose();
await this.callShutdownHook(signal);
this.unsubscribeFromProcessSignals();
}
/**
* Sets custom logger service.
* Flushes buffered logs if auto flush is on.
* @returns {void}
*/
useLogger(logger) {
common_1.Logger.overrideLogger(logger);
if (this.shouldFlushLogsOnOverride) {
this.flushLogs();
}
}
/**
* Prints buffered logs and detaches buffer.
* @returns {void}
*/
flushLogs() {
common_1.Logger.flush();
}
/**
* Define that it must flush logs right after defining a custom logger.
*/
flushLogsOnOverride() {
this.shouldFlushLogsOnOverride = true;
}
/**
* Enables the usage of shutdown hooks. Will call the
* `onApplicationShutdown` function of a provider if the
* process receives a shutdown signal.
*
* @param {ShutdownSignal[]} [signals=[]] The system signals it should listen to
* @param {ShutdownHooksOptions} [options={}] Options for configuring shutdown hooks behavior
*
* @returns {this} The Nest application context instance
*/
enableShutdownHooks(signals = [], options = {}) {
if ((0, shared_utils_1.isEmpty)(signals)) {
signals = Object.keys(common_1.ShutdownSignal).map((key) => common_1.ShutdownSignal[key]);
}
else {
// given signals array should be unique because
// process shouldn't listen to the same signal more than once.
signals = Array.from(new Set(signals));
}
signals = (0, iterare_1.iterate)(signals)
.map((signal) => signal.toString().toUpperCase().trim())
// filter out the signals which is already listening to
.filter(signal => !this.activeShutdownSignals.includes(signal))
.toArray();
this.listenToShutdownSignals(signals, options);
return this;
}
async dispose() {
// Nest application context has no server
// to dispose, therefore just call a noop
return Promise.resolve();
}
/**
* Listens to shutdown signals by listening to
* process events
*
* @param {string[]} signals The system signals it should listen to
* @param {ShutdownHooksOptions} options Options for configuring shutdown hooks behavior
*/
listenToShutdownSignals(signals, options = {}) {
let receivedSignal = false;
const cleanup = async (signal) => {
try {
if (receivedSignal) {
// If we receive another signal while we're waiting
// for the server to stop, just ignore it.
return;
}
receivedSignal = true;
await this.initializationPromise;
await this.callDestroyHook();
await this.callBeforeShutdownHook(signal);
await this.dispose();
await this.callShutdownHook(signal);
signals.forEach(sig => process.removeListener(sig, cleanup));
if (options.useProcessExit) {
// Use process.exit() to ensure the 'exit' event is properly triggered.
// This is required for async loggers (like Pino with transports)
// to flush their buffers before the process terminates.
process.exit(0);
}
else {
process.kill(process.pid, signal);
}
}
catch (err) {
common_1.Logger.error(constants_1.MESSAGES.ERROR_DURING_SHUTDOWN, err?.stack, NestApplicationContext.name);
process.exit(1);
}
};
this.shutdownCleanupRef = cleanup;
signals.forEach((signal) => {
this.activeShutdownSignals.push(signal);
process.on(signal, cleanup);
});
}
/**
* Unsubscribes from shutdown signals (process events)
*/
unsubscribeFromProcessSignals() {
if (!this.shutdownCleanupRef) {
return;
}
this.activeShutdownSignals.forEach(signal => {
process.removeListener(signal, this.shutdownCleanupRef);
});
}
/**
* Calls the `onModuleInit` function on the registered
* modules and its children.
*/
async callInitHook() {
const modulesSortedByDistance = this.getModulesToTriggerHooksOn();
for (const module of modulesSortedByDistance) {
await (0, hooks_1.callModuleInitHook)(module);
}
}
/**
* Calls the `onModuleDestroy` function on the registered
* modules and its children.
*/
async callDestroyHook() {
const modulesSortedByDistance = [
...this.getModulesToTriggerHooksOn(),
].reverse();
for (const module of modulesSortedByDistance) {
await (0, hooks_1.callModuleDestroyHook)(module);
}
}
/**
* Calls the `onApplicationBootstrap` function on the registered
* modules and its children.
*/
async callBootstrapHook() {
const modulesSortedByDistance = this.getModulesToTriggerHooksOn();
for (const module of modulesSortedByDistance) {
await (0, hooks_1.callModuleBootstrapHook)(module);
}
}
/**
* Calls the `onApplicationShutdown` function on the registered
* modules and children.
*/
async callShutdownHook(signal) {
const modulesSortedByDistance = [
...this.getModulesToTriggerHooksOn(),
].reverse();
for (const module of modulesSortedByDistance) {
await (0, hooks_1.callAppShutdownHook)(module, signal);
}
}
/**
* Calls the `beforeApplicationShutdown` function on the registered
* modules and children.
*/
async callBeforeShutdownHook(signal) {
const modulesSortedByDistance = [
...this.getModulesToTriggerHooksOn(),
].reverse();
for (const module of modulesSortedByDistance) {
await (0, hooks_1.callBeforeAppShutdownHook)(module, signal);
}
}
assertNotInPreviewMode(methodName) {
if (this.appOptions.preview) {
const error = `Calling the "${methodName}" in the preview mode is not supported.`;
this.logger.error(error);
throw new Error(error);
}
}
getModulesToTriggerHooksOn() {
if (this._moduleRefsForHooksByDistance) {
return this._moduleRefsForHooksByDistance;
}
const modulesContainer = this.container.getModules();
const compareFn = (a, b) => b.distance - a.distance;
const modulesSortedByDistance = Array.from(modulesContainer.values()).sort(compareFn);
this._moduleRefsForHooksByDistance = this.appOptions?.preview
? modulesSortedByDistance.filter(moduleRef => moduleRef.initOnPreview)
: modulesSortedByDistance;
return this._moduleRefsForHooksByDistance;
}
printInPreviewModeWarning() {
this.logger.warn('------------------------------------------------');
this.logger.warn('Application is running in the PREVIEW mode!');
this.logger.warn('Providers/controllers will not be instantiated.');
this.logger.warn('------------------------------------------------');
}
}
exports.NestApplicationContext = NestApplicationContext;
|