I am currently reading the documentation for a Nest.js application using Prisma. Following the documentation, I have created the following Service.
import { INestApplication, OnModuleInit } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
console.log('onModuleInit PrismaService')
await this.$connect();
}
async enableShutdownHooks(app: INestApplication){
this.$on('beforeExit', async () => {
console.log('PrismaService enableShutdownHooks beforeExit')
await app.close();
});
}
}
The documentation described the use of the following.
import { Module } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CsvParsersModule } from './csv-parsers/csv-parsers.module';
import { PrismaModule } from './prisma/prisma.module';
import { PrismaService } from './prisma/prisma.service';
@Module({
imports: [CsvParsersModule],
controllers: [AppController],
providers: [AppService, PrismaService]
})
export class AppModule {}
However, such code will cause onModuleInit to be called repeatedly when the Service is registered elsewhere.
import { Global, Module } from '@nestjs/common';
import { CsvParsersService } from './csv-parsers.service';
import { CsvParsersController } from './csv-parsers.controller';
import { PrismaService } from 'src/prisma/prisma.service';
@Module({
controllers: [CsvParsersController],
providers: [CsvParsersService, PrismaService],
exports: [CsvParsersService]
})
export class CsvParsersModule {}
[Nest] 78737 - 2022/07/21 8:05:23 LOG [NestFactory] Starting Nest application...
[Nest] 78737 - 2022/07/21 8:05:23 LOG [InstanceLoader] AppModule dependencies initialized +25ms
[Nest] 78737 - 2022/07/21 8:05:23 LOG [InstanceLoader] CsvParsersModule dependencies initialized +0ms
[Nest] 78737 - 2022/07/21 8:05:23 LOG [RoutesResolver] AppController {/}: +8ms
[Nest] 78737 - 2022/07/21 8:05:23 LOG [RouterExplorer] Mapped {/, GET} route +1ms
[Nest] 78737 - 2022/07/21 8:05:23 LOG [RoutesResolver] CsvParsersController {/csv-parsers}: +0ms
[Nest] 78737 - 2022/07/21 8:05:23 LOG [RouterExplorer] Mapped {/csv-parsers, POST} route +0ms
onModuleInit PrismaService
onModuleInit PrismaService
[Nest] 78737 - 2022/07/21 8:05:23 LOG [NestApplication] Nest application successfully started +51ms
I think the best process is for onModuleInit to be called only once. How should this be resolved?
you registered that service twice, that's why you got two instances of the same class.
You can just add it once in some of those modules, then export it to the another one.