8

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?

muturgan
  • 473
  • 1
  • 8
  • 19
  • 1
    Did you try lightship? - https://www.npmjs.com/package/lightship – pravindot17 May 22 '20 at 04:27
  • @pravindot17 very interesting package. thank you. i will learn it. but i try to find a built in nest.js solution – muturgan May 22 '20 at 08:43
  • 1
    What are you using for your DB? I recently got bit in that Prisma hijacks the shutdown signal and kills the process before the nestjs hooks can fire. – meeech May 11 '21 at 17:37

1 Answers1

11

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);
}
JP de la Torre
  • 1,593
  • 18
  • 20