service-template-express/src/routes/health.ts
Noah Holt 2828a630a6
Some checks failed
/ checks (push) Successful in 35s
/ deploy (push) Failing after 2s
feat: initial backend service template
2026-11-05 01:43:18 -06:00

35 lines
1.1 KiB
TypeScript

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<string, string> = {};
let ready = true;
const check = async (name: string, fn?: () => Promise<void>) => {
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;
}