fix(prisma): redirect SQLite file target to writeable /tmp path in serverless contexts

This commit is contained in:
FalahMobile
2026-07-08 19:28:55 +08:00
parent 8861e9143d
commit e2f8d7be66
2 changed files with 39 additions and 4 deletions
+38 -3
View File
@@ -1,7 +1,42 @@
import { PrismaClient } from '@prisma/client'
import fs from 'fs'
import path from 'path'
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
let prisma: PrismaClient
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
if (process.env.LAMBDA_TASK_ROOT || process.env.NETLIFY) {
const targetDbPath = '/tmp/dev.db'
if (!fs.existsSync(targetDbPath)) {
let sourceDbPath = path.join(process.cwd(), 'prisma', 'dev.db')
if (!fs.existsSync(sourceDbPath)) {
sourceDbPath = path.join(process.cwd(), 'dev.db')
}
try {
if (fs.existsSync(sourceDbPath)) {
fs.copyFileSync(sourceDbPath, targetDbPath)
fs.chmodSync(targetDbPath, 0o666)
console.log(`Copied database to writeable path: ${targetDbPath}`)
} else {
console.error(`Database template not found at: ${sourceDbPath}`)
}
} catch (e) {
console.error('Error copying SQLite database to /tmp:', e)
}
}
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
prisma = new PrismaClient({
datasources: {
db: {
url: `file:${targetDbPath}`
}
}
})
} else {
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }
prisma = globalForPrisma.prisma ?? new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
}
export { prisma }