2026-03-12 19:18:01 -05:00
|
|
|
import { PrismaClient } from '@prisma/client'
|
2026-03-12 23:49:58 -05:00
|
|
|
import { PrismaLibSQL } from '@prisma/adapter-libsql'
|
|
|
|
|
import { createClient } from '@libsql/client'
|
2026-03-12 17:09:22 -05:00
|
|
|
|
|
|
|
|
const globalForPrisma = globalThis as unknown as {
|
|
|
|
|
prisma: PrismaClient | undefined
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-12 20:30:36 -05:00
|
|
|
function getPrismaClient(): PrismaClient {
|
2026-03-12 20:27:11 -05:00
|
|
|
if (!globalForPrisma.prisma) {
|
2026-03-12 23:49:58 -05:00
|
|
|
const libsql = createClient({
|
|
|
|
|
url: process.env.DATABASE_URL ?? 'file:./dev.db',
|
|
|
|
|
})
|
|
|
|
|
const adapter = new PrismaLibSQL(libsql)
|
2026-03-12 20:27:11 -05:00
|
|
|
globalForPrisma.prisma = new PrismaClient({
|
2026-03-12 23:49:58 -05:00
|
|
|
adapter,
|
2026-03-12 20:27:11 -05:00
|
|
|
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
return globalForPrisma.prisma
|
|
|
|
|
}
|
2026-03-12 17:09:22 -05:00
|
|
|
|
2026-03-12 20:30:36 -05:00
|
|
|
// Use a Proxy so `new PrismaClient()` is only called when a property
|
|
|
|
|
// is first accessed (inside a request handler), NOT at module import time.
|
|
|
|
|
export const prisma = new Proxy({} as PrismaClient, {
|
|
|
|
|
get(_target, prop) {
|
|
|
|
|
return Reflect.get(getPrismaClient(), prop)
|
|
|
|
|
},
|
|
|
|
|
apply(_target, thisArg, args) {
|
|
|
|
|
return Reflect.apply(getPrismaClient() as unknown as Function, thisArg, args)
|
|
|
|
|
},
|
|
|
|
|
})
|