import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(PrismaService.name); constructor() { super({ // In production set connection_limit and pool_timeout in DATABASE_URL: // ?connection_limit=10&pool_timeout=20&sslmode=require log: process.env.NODE_ENV === 'development' ? [{ emit: 'event', level: 'query' }, { emit: 'stdout', level: 'warn' }, { emit: 'stdout', level: 'error' }] : [{ emit: 'stdout', level: 'warn' }, { emit: 'stdout', level: 'error' }], }); if (process.env.NODE_ENV === 'development') { (this as any).$on('query', (e: { query: string; duration: number }) => { if (e.duration > 500) { this.logger.warn(`Slow query (${e.duration}ms): ${e.query}`); } }); } } async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } }