I enabled shutdown hooks at my bootstrap function. Also I subscribed on application shutdown hook at one of my modules:
public async onApplicationShutdown(signal): Promise<void>
{
console.log({signal});
...
}
Now I can press Ctrl+C and read an excellent message at terminal. Then my resource release works correctly.
Also I want to close my app if db connection failed:
export class MyDbAccessImplementation {
constructor() {
this._pool = createPool(some);
this._pool.query(`SELECT 'test' AS TEST`, (err) => {
if (err !== null) {
console.error(err);
process.emit('SIGINT');
}
});
}
}
But in this case my onApplicationShutdown method does not triggered on db connection error and the application closes instantly.
How I can trigger Nest.js application shutdown from its component?
I believe your problem might be that your NestJS instance is not listening for shutdown events. You need to enable that behavior with app.enableShutdownHooks() in you bootstrap.
This is from their Lifecycles Events guide:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Starts listening for shutdown hooks
app.enableShutdownHooks();
await app.listen(3000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With