From 6b88b196ce3bc5c33e259bea844dc2f95c38f0cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20De=20Boey?= Date: Sat, 8 Jul 2023 15:29:28 +0200 Subject: [PATCH] feat: simplify Prisma setup (#245) --- app/db.server.ts | 22 ++++------------------ app/singleton.server.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+), 18 deletions(-) create mode 100644 app/singleton.server.ts diff --git a/app/db.server.ts b/app/db.server.ts index 643c7629..ac5701fa 100644 --- a/app/db.server.ts +++ b/app/db.server.ts @@ -1,23 +1,9 @@ import { PrismaClient } from "@prisma/client"; -let prisma: PrismaClient; +import { singleton } from "./singleton.server"; -declare global { - var __db__: PrismaClient | undefined; -} - -// This is needed because in development we don't want to restart -// the server with every change, but we want to make sure we don't -// create a new connection to the DB with every change either. -// In production, we'll have a single connection to the DB. -if (process.env.NODE_ENV === "production") { - prisma = new PrismaClient(); -} else { - if (!global.__db__) { - global.__db__ = new PrismaClient(); - } - prisma = global.__db__; - prisma.$connect(); -} +// Hard-code a unique key, so we can look up the client when this module gets re-imported +const prisma = singleton("prisma", () => new PrismaClient()); +prisma.$connect(); export { prisma }; diff --git a/app/singleton.server.ts b/app/singleton.server.ts new file mode 100644 index 00000000..4eae6307 --- /dev/null +++ b/app/singleton.server.ts @@ -0,0 +1,13 @@ +// Since the dev server re-requires the bundle, do some shenanigans to make +// certain things persist across that 😆 +// Borrowed/modified from https://github.com/jenseng/abuse-the-platform/blob/2993a7e846c95ace693ce61626fa072174c8d9c7/app/utils/singleton.ts + +export const singleton = ( + name: string, + valueFactory: () => Value +): Value => { + const g = global as any; + g.__singletons ??= {}; + g.__singletons[name] ??= valueFactory(); + return g.__singletons[name]; +};