work-timer/app/db.server.ts

50 lines
1.4 KiB
TypeScript
Raw Normal View History

import { PrismaClient } from '@prisma/client';
import invariant from 'tiny-invariant';
2023-02-11 03:14:14 +01:00
invariant(process.env.DATABASE_URL, 'DATABASE_URL must be set');
const DATABASE_URL = process.env.DATABASE_URL;
2023-02-11 03:14:14 +01:00
let prisma: PrismaClient;
2023-02-11 03:14:14 +01:00
declare global {
var __db__: PrismaClient;
2023-02-11 03:14:14 +01:00
}
// 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 = getClient();
2023-02-11 03:14:14 +01:00
} else {
if (!global.__db__) {
global.__db__ = getClient();
2023-02-11 03:14:14 +01:00
}
prisma = global.__db__;
2023-02-11 03:14:14 +01:00
}
function getClient() {
invariant(typeof DATABASE_URL === 'string', 'DATABASE_URL env var not set');
2023-02-11 03:14:14 +01:00
const databaseUrl = new URL(DATABASE_URL);
2023-02-11 03:14:14 +01:00
console.log(`🔌 setting up prisma client to ${databaseUrl.host}`);
2023-02-11 03:14:14 +01:00
// NOTE: during development if you change anything in this function, remember
// that this only runs once per server restart and won't automatically be
// re-run per request like everything else is. So if you need to change
// something in this file, you'll need to manually restart the server.
const client = new PrismaClient({
datasources: {
db: {
url: databaseUrl.toString()
}
}
});
2023-02-11 03:14:14 +01:00
// connect eagerly
client.$connect();
2023-02-11 03:14:14 +01:00
return client;
2023-02-11 03:14:14 +01:00
}
export { prisma };