fosrl.pangolin/server/db/pg/driver.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-06-04 12:02:07 -04:00
import { drizzle as DrizzlePostgres } from "drizzle-orm/node-postgres";
2025-07-13 21:57:24 -07:00
import { Pool } from "pg";
2025-06-04 12:02:07 -04:00
import { readConfigFile } from "@server/lib/readConfigFile";
2025-06-13 13:04:21 -04:00
import { withReplicas } from "drizzle-orm/pg-core";
2025-06-04 12:02:07 -04:00
function createDb() {
const config = readConfigFile();
if (!config.postgres) {
throw new Error(
"Postgres configuration is missing in the configuration file."
);
}
2025-06-04 12:02:07 -04:00
const connectionString = config.postgres?.connection_string;
2025-06-13 13:04:21 -04:00
const replicaConnections = config.postgres?.replicas || [];
2025-06-04 12:02:07 -04:00
if (!connectionString) {
2025-06-13 13:04:21 -04:00
throw new Error(
"A primary db connection string is required in the configuration file."
);
2025-06-04 12:02:07 -04:00
}
2025-07-13 21:57:24 -07:00
// Create connection pools instead of individual connections
const primaryPool = new Pool({
connectionString,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
2025-06-13 13:04:21 -04:00
const replicas = [];
if (!replicaConnections.length) {
2025-07-13 21:57:24 -07:00
replicas.push(DrizzlePostgres(primaryPool));
2025-06-13 13:04:21 -04:00
} else {
for (const conn of replicaConnections) {
2025-07-13 21:57:24 -07:00
const replicaPool = new Pool({
connectionString: conn.connection_string,
max: 10,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
replicas.push(DrizzlePostgres(replicaPool));
2025-06-13 13:04:21 -04:00
}
}
2025-07-13 21:57:24 -07:00
return withReplicas(DrizzlePostgres(primaryPool), replicas as any);
2025-06-04 12:02:07 -04:00
}
export const db = createDb();
export default db;