-
Notifications
You must be signed in to change notification settings - Fork 236
/
db.server.ts
51 lines (39 loc) · 1.56 KB
/
db.server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { PrismaClient } from "@prisma/client";
import invariant from "tiny-invariant";
import { singleton } from "./singleton.server";
// Hard-code a unique key, so we can look up the client when this module gets re-imported
const prisma = singleton("prisma", getPrismaClient);
function getPrismaClient() {
const { DATABASE_URL } = process.env;
invariant(typeof DATABASE_URL === "string", "DATABASE_URL env var not set");
const databaseUrl = new URL(DATABASE_URL);
const isLocalHost = databaseUrl.hostname === "localhost";
const PRIMARY_REGION = isLocalHost ? null : process.env.PRIMARY_REGION;
const FLY_REGION = isLocalHost ? null : process.env.FLY_REGION;
const isReadReplicaRegion = !PRIMARY_REGION || PRIMARY_REGION === FLY_REGION;
if (!isLocalHost) {
if (databaseUrl.host.endsWith(".internal")) {
databaseUrl.host = `${FLY_REGION}.${databaseUrl.host}`;
}
if (!isReadReplicaRegion) {
// 5433 is the read-replica port
databaseUrl.port = "5433";
}
}
console.log(`🔌 setting up prisma client to ${databaseUrl.host}`);
// 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(),
},
},
});
// connect eagerly
client.$connect();
return client;
}
export { prisma };