import { PrismaPg } from '@prisma/adapter-pg'; import { PrismaClient } from '@/lib/generated/prisma/client'; /** * The Prisma client, created on first use rather than on import. * * Next imports every route module while collecting page data at build time, in * a container that has no database and no DATABASE_URL. A module that threw on * import would fail the build with an error pointing at whichever route * happened to be analysed first, which says nothing useful. Creating the * client lazily moves that failure to the first actual query, where the * message is about the database because the problem is. */ const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient }; function client(): PrismaClient { if (globalForPrisma.prisma) { return globalForPrisma.prisma; } const connectionString = process.env.DATABASE_URL; if (!connectionString) { throw new Error( 'DATABASE_URL n’est pas défini : impossible de joindre la base de données.', ); } const created = new PrismaClient({ adapter: new PrismaPg({ connectionString }) }); // Next hot-reloads modules in development; without this the dev server would // open a new pool on every edit until Postgres refuses connections. if (process.env.NODE_ENV !== 'production') { globalForPrisma.prisma = created; } return created; } let singleton: PrismaClient | undefined; function instance(): PrismaClient { singleton ??= client(); return singleton; } export const prisma: PrismaClient = new Proxy({} as PrismaClient, { get(_target, property) { const target = instance(); const value = Reflect.get(target, property) as unknown; // Model delegates and methods both need their original `this`. return typeof value === 'function' ? value.bind(target) : value; }, });