/** * apps/worker — Prisma client singleton. * * One PrismaClient per process (the worker's only Postgres handle). The * generated client comes from the monorepo schema (prisma/schema.prisma). * `getPrisma()` connects lazily on first use; `closePrisma()` is called on * graceful shutdown. */ import { Prisma, PrismaClient } from "@prisma/client"; import { getLogger } from "../logger.js"; const log = getLogger("prisma"); let client: PrismaClient | null = null; /** * Type bridge for Prisma JSONB inputs. Runtime values we build (maps with * unknown values, scan reports, payloads) are JSON-serializable; this cast * asserts that once, here, instead of scattering `as any` through callers. */ export const asJson = (v: unknown): Prisma.InputJsonValue => v as Prisma.InputJsonValue; export function getPrisma(): PrismaClient { if (!client) { client = new PrismaClient({ log: process.env.NODE_ENV === "development" ? ["warn", "error"] : ["error"] }); } return client; } /** Connect explicitly at startup (surfaces bad DATABASE_URL early). */ export async function connectPrisma(): Promise { const prisma = getPrisma(); await prisma.$connect(); log.debug("prisma connected"); return prisma; } export async function closePrisma(): Promise { if (client) { await client.$disconnect(); client = null; log.debug("prisma disconnected"); } }