UNPKG

@nestjs/core

Version:

Nest - modern, fast, powerful node.js web framework (@core)

47 lines (46 loc) 1.92 kB
import { isFunction, isNil } from '@nestjs/common/internal'; import { iterate } from 'iterare'; import { getInstancesGroupedByHierarchyLevel } from './utils/get-instances-grouped-by-hierarchy-level.js'; import { getSortedHierarchyLevels } from './utils/get-sorted-hierarchy-levels.js'; /** * Checks if the given instance has the `onApplicationBootstrap` function * * @param instance The instance which should be checked */ function hasOnAppBootstrapHook(instance) { return isFunction(instance.onApplicationBootstrap); } /** * Calls the given instances */ function callOperator(instances) { return iterate(instances) .filter(instance => !isNil(instance)) .filter(hasOnAppBootstrapHook) .map(async (instance) => instance.onApplicationBootstrap()) .toArray(); } /** * Calls the `onApplicationBootstrap` function on the module and its children * (providers / controllers). * * @param moduleRef The module which will be initialized */ export async function callModuleBootstrapHook(moduleRef) { const providers = moduleRef.getNonAliasProviders(); // Module (class) instance is the first element of the providers array // Lifecycle hook has to be called once all classes are properly initialized const [_, moduleClassHost] = providers.shift(); const groupedInstances = getInstancesGroupedByHierarchyLevel(moduleRef.controllers, moduleRef.injectables, moduleRef.middlewares, providers); const levels = getSortedHierarchyLevels(groupedInstances); for (const level of levels) { await Promise.all(callOperator(groupedInstances.get(level))); } // Call the instance itself const moduleClassInstance = moduleClassHost.instance; if (moduleClassInstance && hasOnAppBootstrapHook(moduleClassInstance) && moduleClassHost.isDependencyTreeStatic()) { await moduleClassInstance.onApplicationBootstrap(); } }