Prisma as an Alternative

Prisma is a modern, type-safe ORM you can wrap in an injectable Nest service.

Syntaxclass PrismaService extends PrismaClient

Prisma 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

  1. Define your models in schema.prisma and run prisma generate.
  2. Create a PrismaService that extends PrismaClient and connects on module init.
  3. Inject PrismaService into your feature services.

This keeps Prisma inside the familiar Nest dependency injection model.

Example

Example Β· typescript
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.

Example Β· bash
npm install prisma @prisma/client
npx prisma init --datasource-provider postgresql

PrismaService provider

Wraps PrismaClient in a NestJS service that connects when the module initializes and disconnects on teardown.

Example Β· ts
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.

Example Β· ts
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

  • Be the first to comment on this lesson.