43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import path from "node:path"
|
|
|
|
import { PrismaClient } from "@prisma/client"
|
|
|
|
declare global {
|
|
var prisma: PrismaClient | undefined
|
|
}
|
|
|
|
// Resolve a robust DATABASE_URL for all runtimes (prod/dev)
|
|
function resolveFileUrl(url: string) {
|
|
if (!url.startsWith("file:")) {
|
|
return url
|
|
}
|
|
|
|
const filePath = url.slice("file:".length)
|
|
if (filePath.startsWith("./") || filePath.startsWith("../")) {
|
|
const schemaDir = path.resolve(process.cwd(), "prisma")
|
|
const absolutePath = path.resolve(schemaDir, filePath)
|
|
return `file:${absolutePath}`
|
|
}
|
|
if (!filePath.startsWith("/")) {
|
|
const absolutePath = path.resolve(process.cwd(), filePath)
|
|
return `file:${absolutePath}`
|
|
}
|
|
return url
|
|
}
|
|
|
|
const resolvedDatabaseUrl = (() => {
|
|
const envUrl = process.env.DATABASE_URL?.trim()
|
|
if (envUrl && envUrl.length > 0) return resolveFileUrl(envUrl)
|
|
// Fallbacks by environment to ensure correctness in containers
|
|
if (process.env.NODE_ENV === "production") {
|
|
return "file:/app/data/db.sqlite"
|
|
}
|
|
return resolveFileUrl("file:./prisma/db.sqlite")
|
|
})()
|
|
|
|
export const prisma =
|
|
global.prisma ?? new PrismaClient({ datasources: { db: { url: resolvedDatabaseUrl } } })
|
|
|
|
if (process.env.NODE_ENV !== "production") {
|
|
global.prisma = prisma
|
|
}
|