UNPKG

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