templates2.Store.Nuxt/server/utils/db.ts
w4c-templates 228f2f01f2
Some checks failed
CI / quality (push) Has been cancelled
chore(template): publish Store.Nuxt
2026-10-11 23:24:30 +03:00

25 lines
1 KiB
TypeScript

import { PrismaClient } from '@prisma/client';
import path from 'node:path';
/**
* The Prisma CLI resolves a relative SQLite path (`file:./dev.db`) against the schema directory
* (`prisma/`), but inside a bundled Nitro output it would resolve against the copied client and
* open an empty database. Resolve relative sqlite paths against `<cwd>/prisma` so the runtime and
* the CLI always agree. Absolute paths and non-sqlite URLs are passed through unchanged.
*/
function resolveDatabaseUrl(): string | undefined {
const url = process.env.DATABASE_URL;
if (!url || !url.startsWith('file:')) return url;
const file = url.slice('file:'.length);
if (path.isAbsolute(file)) return url;
return `file:${path.resolve(process.cwd(), 'prisma', file)}`;
}
// A single PrismaClient per process.
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const db =
globalForPrisma.prisma ?? new PrismaClient({ datasources: { db: { url: resolveDatabaseUrl() } } });
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db;