40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import { PrismaClient } from '@prisma/client'
|
|
|
|
const globalForPrisma = globalThis as unknown as {
|
|
prisma: PrismaClient | undefined
|
|
}
|
|
|
|
// Detect database provider from environment (default to sqlite for local development)
|
|
// Next.js automatically loads environment variables from .env, .env.development, .env.production
|
|
const databaseProvider = process.env.DATABASE_PROVIDER || 'sqlite'
|
|
const databaseUrl = process.env.DATABASE_URL
|
|
|
|
// Create PrismaClient with appropriate adapter
|
|
const createPrismaClient = () => {
|
|
let client: PrismaClient
|
|
|
|
if (databaseProvider === 'postgresql') {
|
|
// Validate DATABASE_URL is present for PostgreSQL
|
|
if (!databaseUrl) {
|
|
throw new Error(
|
|
'DATABASE_URL environment variable is required when DATABASE_PROVIDER is set to postgresql. ' +
|
|
'Current DATABASE_PROVIDER: ' + databaseProvider
|
|
)
|
|
}
|
|
|
|
// Use PrismaPg adapter for PostgreSQL
|
|
const { PrismaPg } = require('@prisma/adapter-pg')
|
|
const adapter = new PrismaPg({ connectionString: databaseUrl })
|
|
client = new PrismaClient({ adapter })
|
|
} else {
|
|
// No adapter needed for SQLite
|
|
client = new PrismaClient()
|
|
}
|
|
|
|
return client
|
|
}
|
|
|
|
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
|
|
|
|
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|