30 lines
848 B
TypeScript
30 lines
848 B
TypeScript
import { PrismaClient } from '@prisma/client';
|
|
import { PrismaPg } from '@prisma/adapter-pg';
|
|
|
|
// Singleton pattern for Prisma client - prevents "Too many database connections" error
|
|
const globalForPrisma = globalThis as unknown as {
|
|
prisma: PrismaClient | undefined;
|
|
};
|
|
|
|
function createPrismaClient() {
|
|
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
|
|
|
return new PrismaClient({
|
|
adapter,
|
|
log: process.env.NODE_ENV === 'dev' ? ['query', 'info', 'warn', 'error'] : ['error'],
|
|
});
|
|
}
|
|
|
|
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
globalForPrisma.prisma = prisma;
|
|
}
|
|
|
|
// For serverless environments, always cache the client
|
|
if (process.env.IS_OFFLINE || process.env.AWS_LAMBDA_FUNCTION_NAME) {
|
|
globalForPrisma.prisma = prisma;
|
|
}
|
|
|
|
|