Ga naar hoofdinhoud

Plugin Lifecycle Hooks

Understand the plugin initialization and teardown lifecycle.

Lifecycle Phases​

NestJS Lifecycle Hooks​

HookWhen Called
onModuleInit()After module instantiation
onApplicationBootstrap()After all modules initialized
onModuleDestroy()Before module teardown
beforeApplicationShutdown()Before app stops

Implementation​

import {
Module,
OnModuleInit,
OnApplicationBootstrap,
OnModuleDestroy,
} from "@nestjs/common";

@Module({
/* ... */
})
export class MyPluginModule
implements OnModuleInit, OnApplicationBootstrap, OnModuleDestroy
{
async onModuleInit() {
console.log("Plugin module initialized");
// Register entities, set up connections
}

async onApplicationBootstrap() {
console.log("Application fully started");
// Start background tasks, subscribe to events
}

async onModuleDestroy() {
console.log("Plugin shutting down");
// Cleanup connections, stop timers
}
}

Common Init Tasks​

PhaseTasks
onModuleInitRegister entities, validate config
onApplicationBootstrapStart schedulers, connect to external services
onModuleDestroyClose connections, flush queues