Files
lunch/lib/db.ts
T
kai d1bf5196dd
release / which version (push) Successful in 1s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 1m7s
release / tag and release (push) Successful in 2s
Own sign-in with passkeys, public entrance, market (26.11.2) (#3)
2026-11-06 19:32:34 +00:00

77 lines
2.6 KiB
TypeScript

import "server-only";
import { Pool, type PoolClient } from "pg";
// Zugang zur Postgres von Olares. Die Werte injiziert das Chart aus
// .Values.postgres.* (CLAUDE.md, Olares-Regel 5) — nie hartkodieren.
// Lokal reicht DATABASE_URL.
function createPool(): Pool {
if (process.env.DATABASE_URL) return new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
return new Pool({
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT ?? 5432),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
max: 10,
});
}
const globalForPool = globalThis as unknown as { lunchPool?: Pool };
export const pool: Pool = globalForPool.lunchPool ?? createPool();
if (process.env.NODE_ENV !== "production") globalForPool.lunchPool = pool;
/**
* Führt `fn` in einer Transaktion im Namen eines Haushalts aus.
*
* Jede Fachtabelle hat RLS mit FORCE und die Policy „Mitglied des Haushalts“
* über `app.household_id`. Ohne diesen Aufruf sieht eine Abfrage nichts —
* die App verbindet als Tabelleneigentümerin, FORCE ist die einzige Wand.
* `set_config(…, true)` gilt nur bis zum Ende der Transaktion; ein Client,
* der in den Pool zurückgeht, trägt keinen Haushalt weiter.
*/
export async function withHousehold<T>(householdId: string, fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
await client.query("begin");
await client.query("select set_config('app.household_id', $1, true)", [householdId]);
const result = await fn(client);
await client.query("commit");
return result;
} catch (error) {
await client.query("rollback").catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/**
* Für die Anmeldung, bevor der Haushalt bekannt ist: setzt `app.auth = on`.
* Die Policies lassen das nur auf den Tabellen der Anmeldung zu (Migration
* 0002). Außerhalb von lib/auth/ nie benutzen.
*/
export async function withAuth<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
await client.query("begin");
await client.query("select set_config('app.auth', 'on', true)");
const result = await fn(client);
await client.query("commit");
return result;
} catch (error) {
await client.query("rollback").catch(() => undefined);
throw error;
} finally {
client.release();
}
}
export async function databaseReachable(): Promise<boolean> {
try {
await pool.query("select 1");
return true;
} catch {
return false;
}
}