Performance: Prisma setup in NestJS
This affects server response time and API data fetching speed, impacting how fast the frontend receives data.
import { PrismaClient } from '@prisma/client'; import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } } @Injectable() export class UserService { constructor(private prisma: PrismaService) {} async getUsers() { return await this.prisma.user.findMany(); } }
import { Injectable } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class UserService { private prisma = new PrismaClient(); async getUsers() { return await this.prisma.user.findMany(); } }
| Pattern | DB Connections | Memory Usage | Response Latency | Verdict |
|---|---|---|---|---|
| Direct PrismaClient in service | Multiple per service instance | High | Higher due to connection overhead | [X] Bad |
| Singleton PrismaService with DI | Single shared connection | Low | Lower due to reuse | [OK] Good |
PrismaService in a NestJS application?console.log(user) output if the user with ID 1 exists?
async getUserById(id: number) {
return this.prisma.user.findUnique({ where: { id } });
}
const user = await prismaService.getUserById(1);
console.log(user);Cannot read property 'user' of undefined. What is the likely cause?
async getAllUsers() {
return this.prisma.user.findMany();
}
Options:this.prisma is undefined in the service.this.prisma in the constructor; missing this causes the error.findMany with include: { author: true } to load related author data.Pass the test and this pattern moves unknown