@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
}
@Module({ providers: [PrismaService], exports: [PrismaService] })
export class PrismaModule {}
Wrap the generated PrismaClient in a Nest provider. Prisma doesn't need a special Nest module.
The steps:
- Define the schema in
schema.prisma. - Run the generator. It produces a typed
PrismaClient. - Create a
PrismaServicethat extendsPrismaClient. - Call
$connect()inonModuleInit. This opens the connection at startup. Otherwise Prisma connects lazily, on the first query. - Export
PrismaServicefrom aPrismaModule. This module is often marked global. - Inject
PrismaServiceinto feature services. They call typed methods likethis.prisma.user.findUnique(...).
In tests, you can replace PrismaService with a mock. Use overrideProvider or a useValue provider.
Schema changes go through prisma migrate. They don't happen at runtime.
- Generate a typed client from
schema.prisma. - Create a
PrismaServicethat extendsPrismaClient. - Call
$connect()inonModuleInitto connect at startup. - Export the service from a module, often a global one, and inject it.
- Run schema migrations with
prisma migrate.
Read more
- Prisma recipe (https://docs.nestjs.com/recipes/prisma)docs.nestjs.com
- Prisma docs (https://www.prisma.io/docs)prisma.io