Skip to content

Commit

Permalink
feat: simplify Prisma setup (#245)
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelDeBoey authored Jul 8, 2023
1 parent e02ab14 commit 6b88b19
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
22 changes: 4 additions & 18 deletions app/db.server.ts
Original file line number Diff line number Diff line change
@@ -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 };
13 changes: 13 additions & 0 deletions app/singleton.server.ts
Original file line number Diff line number Diff line change
@@ -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 = <Value>(
name: string,
valueFactory: () => Value
): Value => {
const g = global as any;
g.__singletons ??= {};
g.__singletons[name] ??= valueFactory();
return g.__singletons[name];
};

0 comments on commit 6b88b19

Please sign in to comment.