CodePark/ questions / Database integration (TypeORM / Prisma)
START PRACTICINGPRACTICE
Backend question · NestJS › Database integration (TypeORM / Prisma)

How do you integrate Prisma into a Nest app?

@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 PrismaService that extends PrismaClient.
  • Call $connect() in onModuleInit. This opens the connection at startup. Otherwise Prisma connects lazily, on the first query.
  • Export PrismaService from a PrismaModule. This module is often marked global.
  • Inject PrismaService into feature services. They call typed methods like this.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 PrismaService that extends PrismaClient.
  • Call $connect() in onModuleInit to connect at startup.
  • Export the service from a module, often a global one, and inject it.
  • Run schema migrations with prisma migrate.