UNPKG

2.17 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.callModuleDestroyHook = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5const iterare_1 = require("iterare");
6const transient_instances_1 = require("../injector/helpers/transient-instances");
7/**
8 * Returns true or false if the given instance has a `onModuleDestroy` function
9 *
10 * @param instance The instance which should be checked
11 */
12function hasOnModuleDestroyHook(instance) {
13 return (0, shared_utils_1.isFunction)(instance.onModuleDestroy);
14}
15/**
16 * Calls the given instances onModuleDestroy hook
17 */
18function callOperator(instances) {
19 return (0, iterare_1.iterate)(instances)
20 .filter(instance => !(0, shared_utils_1.isNil)(instance))
21 .filter(hasOnModuleDestroyHook)
22 .map(async (instance) => instance.onModuleDestroy())
23 .toArray();
24}
25/**
26 * Calls the `onModuleDestroy` function on the module and its children
27 * (providers / controllers).
28 *
29 * @param module The module which will be initialized
30 */
31async function callModuleDestroyHook(module) {
32 const providers = module.getNonAliasProviders();
33 // Module (class) instance is the first element of the providers array
34 // Lifecycle hook has to be called once all classes are properly destroyed
35 const [_, moduleClassHost] = providers.shift();
36 const instances = [
37 ...module.controllers,
38 ...providers,
39 ...module.injectables,
40 ...module.middlewares,
41 ];
42 const nonTransientInstances = (0, transient_instances_1.getNonTransientInstances)(instances);
43 await Promise.all(callOperator(nonTransientInstances));
44 const transientInstances = (0, transient_instances_1.getTransientInstances)(instances);
45 await Promise.all(callOperator(transientInstances));
46 // Call the module instance itself
47 const moduleClassInstance = moduleClassHost.instance;
48 if (moduleClassInstance &&
49 hasOnModuleDestroyHook(moduleClassInstance) &&
50 moduleClassHost.isDependencyTreeStatic()) {
51 await moduleClassInstance.onModuleDestroy();
52 }
53}
54exports.callModuleDestroyHook = callModuleDestroyHook;