Home > database >  I am trying to clear typeorm mysql database on server shutdown (NestJS)
I am trying to clear typeorm mysql database on server shutdown (NestJS)

Time:06-25

How do I delete all entries in my database on server shutdown?

export class RoomsService {
  async onApplicationShutdown() {
    await this.roomService.deleteAll()
  }
async deleteAll(): Promise<DeleteResult> {
    const res = await this.roomRepository.delete('*');
    return res;
  } 

On shutdown I get this error (even when I don't use async await)

Error: Pool is closed.
at C:\Users\Admin\Desktop\sites\UltimatePartyRoom\upr-server\node_modules\mysql2\lib\pool.js:39:40
at processTicksAndRejections (node:internal/process/task_queues:77:11)

CodePudding user response:

The problem is that on application shutdown point (onApplicationShutdown) the database connection is already disconnected so you need clear database before reaching this point.

Use OnModuleDestroy instead:

export class RoomsService implements OnModuleDestroy {
  async onModuleDestroy() {
    await this.roomService.deleteAll()
  }
}
  • Related