SPB Git forge

spb/fetcha

Public
11commits 1branches 0releases
1.5 MBsize
maindefault branch
16 days agolast push
TypeScript 97.5% SQL 1.4% Python 0.8%
1.3 KB · 47 lines typescript
Raw Blame History
1import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";2import pg from "pg";3import * as schema from "./schema";45export * from "./schema";6export * as schema from "./schema";7export { sql, eq, and, or, desc, asc, gte, lte, lt, gt, ne, inArray, isNull, isNotNull, count, sum, avg, like, ilike, between } from "drizzle-orm";89export type Db = NodePgDatabase<typeof schema>;1011let _pool: pg.Pool | null = null;12let _db: Db | null = null;1314export function getPool(): pg.Pool {15  if (!_pool) {16    const connectionString = process.env.DATABASE_URL ?? "postgres://localhost:5432/fetcha";17    _pool = new pg.Pool({18      connectionString,19      max: Number(process.env.DB_POOL_MAX ?? 10),20      idleTimeoutMillis: 30_000,21      connectionTimeoutMillis: 10_000,22    });23    _pool.on("error", (err) => console.error("[db] pool error", err.message));24  }25  return _pool;26}2728export function getDb(): Db {29  if (!_db) _db = drizzle(getPool(), { schema, casing: "snake_case" });30  return _db;31}3233/** Lazily-initialised shared database handle. */34export const db: Db = new Proxy({} as Db, {35  get(_t, prop) {36    return (getDb() as unknown as Record<PropertyKey, unknown>)[prop];37  },38});3940export async function closeDb(): Promise<void> {41  if (_pool) {42    await _pool.end();43    _pool = null;44    _db = null;45  }46}47