Refactor database access by introducing prisma.lambda.service for centralized PrismaClient usage across modules. Update imports in various handlers and services to utilize the new service, ensuring consistent database interactions and improved maintainability.
This commit is contained in:
22
src/common/database/prisma.lambda.service.ts
Normal file
22
src/common/database/prisma.lambda.service.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
|
||||
const adapter = new PrismaPg({
|
||||
connectionString: process.env.DATABASE_URL!,
|
||||
});
|
||||
|
||||
let prisma: PrismaClient;
|
||||
|
||||
if (!(global as any).prisma) {
|
||||
(global as any).prisma = new PrismaClient({
|
||||
adapter,
|
||||
log:
|
||||
process.env.NODE_ENV === 'dev'
|
||||
? ['query', 'info', 'warn', 'error']
|
||||
: ['error'],
|
||||
});
|
||||
}
|
||||
|
||||
prisma = (global as any).prisma;
|
||||
|
||||
export const prismaClient = prisma;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
import { PrismaService } from './prisma.lambda.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy, INestApplication } from '@nestjs/common';
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
constructor() {
|
||||
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
||||
super({
|
||||
adapter,
|
||||
log: process.env.NODE_ENV === 'dev' ? ['query', 'info', 'warn', 'error'] : ['error'],
|
||||
});
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
@@ -19,10 +10,4 @@ export class PrismaService extends PrismaClient implements OnModuleInit, OnModul
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
|
||||
async enableShutdownHooks(app: INestApplication) {
|
||||
process.on('beforeExit', async () => {
|
||||
await app.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user