Prisma as an Alternative
Prisma is a modern, type-safe ORM you can wrap in an injectable Nest service.
Syntax
class PrismaService extends PrismaClientPrisma is a popular alternative to TypeORM. It generates a fully type-safe client from a schema file. Nest has no official Prisma module, but integration is simple: wrap the Prisma client in an injectable service.
The pattern
- Define your models in
schema.prismaand runprisma generate. - Create a
PrismaServicethat extendsPrismaClientand connects on module init. - Inject
PrismaServiceinto your feature services.
This keeps Prisma inside the familiar Nest dependency injection model.
Example
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
}
// Inject it and query:
// constructor(private prisma: PrismaService) {}
// this.prisma.user.findMany();When to use it
- A developer replaces TypeORM with Prisma to get a generated, fully type-safe client where every query result is typed without writing extra interfaces.
- A team uses Prisma migrations to version the database schema in source control instead of relying on synchronize:true.
- An engineer wraps the PrismaClient in an @Injectable PrismaService to manage connection lifecycle (connect on init, disconnect on destroy) within the Nest DI container.
More examples
Install and initialize Prisma
Installs Prisma and creates the prisma/schema.prisma file and a .env with a DATABASE_URL placeholder.
npm install prisma @prisma/client
npx prisma init --datasource-provider postgresqlPrismaService provider
Wraps PrismaClient in a NestJS service that connects when the module initializes and disconnects on teardown.
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient
implements OnModuleInit, OnModuleDestroy {
async onModuleInit() { await this.$connect(); }
async onModuleDestroy() { await this.$disconnect(); }
}Using PrismaService in a service
Injects PrismaService and uses the auto-generated user model client to query and create users with full type safety.
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class UsersService {
constructor(private prisma: PrismaService) {}
findAll() {
return this.prisma.user.findMany();
}
create(data: { name: string; email: string }) {
return this.prisma.user.create({ data });
}
}
Discussion