Search code examples
nestjsmikro-orm

How to tear down MikroOrm in NestJS


I've recently converted my AppModule to a dynamic module so that I'm able to provide different configurations to MikroOrm depending on context (E2E tests, etc) and it currently looks like this:

@Module({
  imports: [
    MikroOrmModule.forFeature({
      entities: [Todo],
    }),
  ],
  providers: [TodoService],
  controllers: [AppController, TodosController],
})
export class AppModule {
  static register(options?: {
    mikroOrmOptions?: MikroOrmModuleOptions;
  }): DynamicModule {
    return {
      module: AppModule,
      imports: [
        MikroOrmModule.forRoot({
          entities: [Todo],
          type: 'postgresql',
          host: process.env.DB_HOST,
          port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 5432,
          user: process.env.DB_USER,
          password: process.env.DB_PASS,
          dbName: process.env.DB_DB,

          ...options?.mikroOrmOptions,
        }),
      ],
    };
  }
}

Now I'm trying to ensure graceful shutdown of the app by disconnecting from the database, but not sure where to place a life-cycle hook in this case. It doesn't seem to be possible to have a dynamic module with life-cycle hooks, so I'm thinking of developing a separate provider that injects the orm and write the hook on that.

What would be the correct approach? Thanks.

Edit:

I came up with the following solution. Would appreciate someone indicating if this is the best way:

import { MikroORM } from 'mikro-orm';
...

@Module({
  imports: [
    MikroOrmModule.forFeature({
      entities: [Todo],
    }),
  ],
  providers: [TodoService],
  controllers: [AppController, TodosController],
})
export class AppModule implements OnModuleDestroy {
  static register(options?: {
    mikroOrmOptions?: MikroOrmModuleOptions;
  }): DynamicModule {
    return {
      module: AppModule,
      imports: [
        MikroOrmModule.forRoot({
          entities: [Todo],

          type: 'postgresql',
          host: process.env.DB_HOST,
          port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 5432,
          user: process.env.DB_USER,
          password: process.env.DB_PASS,
          dbName: process.env.DB_DB,

          ...options?.mikroOrmOptions,
        }),
      ],
    };
  }

  constructor(private orm: MikroORM) {}

  async onModuleDestroy(): Promise<void> {
    await this.orm.close();
  }
}



Solution

  • As discussed in the issues, I would go with the way nestjs/typeorm is using, so using onApplicationShutdown hook.

    Also linking the issue here for possible future readers:

    https://github.com/dario1985/nestjs-mikro-orm/issues/10