Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created October 10, 2024 05:53
Show Gist options
  • Save mizchi/7f3a709767992543b0d3285f5de69837 to your computer and use it in GitHub Desktop.
Save mizchi/7f3a709767992543b0d3285f5de69837 to your computer and use it in GitHub Desktop.
Get prisma in cf workers
import { PrismaClient } from "@prisma/client";
import { PrismaPg as PrismaPgWorker } from "@prisma/adapter-pg-worker";
import { Pool } from "@prisma/pg-worker";
let _db: PrismaClient | null = null;
export async function getPrismaClient(env: Env): Promise<PrismaClient> {
if (_db) return _db;
if (import.meta.env.DEV) {
const { default: pg } = await import("pg");
const { PrismaPg } = await import("@prisma/adapter-pg");
const pool = new pg.Pool({
connectionString: env.DATABASE_URL + "&connection_limit=1",
});
const adapter = new PrismaPg(pool);
_db = new PrismaClient({ adapter });
return _db;
} else {
const pool = new Pool({
connectionString: env.DATABASE_URL,
});
const adapter = new PrismaPgWorker(pool);
_db = new PrismaClient({ adapter });
return _db;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment