SPB Git forge

spb/cancerindex

Public
37commits 1branches 0releases
2.9 MBsize
maindefault branch
10 days agolast push
TypeScript 97.2% SQL 1.5% CSS 0.6% JavaScript 0.5%
1.1 KB · 43 lines typescript
Raw Blame History
1import postgres from 'postgres';2import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js';3import * as schema from './schema/index.js';45export type Database = PostgresJsDatabase<typeof schema>;67let _sql: ReturnType<typeof postgres> | null = null;8let _db: Database | null = null;910export interface DbOptions {11  url?: string;12  max?: number;13}1415/** Lazily created singleton; safe from Next.js server components, Fastify and workers alike. */16export function getSql(opts: DbOptions = {}) {17  if (!_sql) {18    const url = opts.url ?? process.env.DATABASE_URL ?? 'postgres://localhost:5432/cancerindex';19    _sql = postgres(url, {20      max: opts.max ?? Number(process.env.DB_POOL_MAX ?? 10),21      idle_timeout: 30,22      connect_timeout: 10,23      prepare: true,24      transform: { undefined: null },25      onnotice: () => {},26    });27  }28  return _sql;29}3031export function getDb(opts: DbOptions = {}): Database {32  if (!_db) _db = drizzle(getSql(opts), { schema, casing: 'snake_case' });33  return _db;34}3536export async function closeDb(): Promise<void> {37  if (_sql) {38    await _sql.end({ timeout: 5 });39    _sql = null;40    _db = null;41  }42}43