import { Router } from "express"; import type { Db } from "../lib/db.js"; import type { Cache } from "../lib/redis.js"; export function healthRouter(deps: { db?: Db; cache?: Cache }): Router { const router = Router(); // Liveness: 200 whenever the process is listening. router.get("/healthz", (_req, res) => { res.type("text/plain").send("ok"); }); // Readiness: every configured backend must answer. router.get("/readyz", async (_req, res) => { const body: Record = {}; let ready = true; const check = async (name: string, fn?: () => Promise) => { if (!fn) return; try { await fn(); body[name] = "ok"; } catch (err) { ready = false; body[name] = `unavailable: ${(err as Error).message || "error"}`; } }; await check("postgres", deps.db && (() => deps.db!.ping())); await check("redis", deps.cache && (() => deps.cache!.ping())); res .status(ready ? 200 : 503) .json({ status: ready ? "ready" : "not-ready", ...body }); }); return router; }