78 lines
2.8 KiB
TypeScript
78 lines
2.8 KiB
TypeScript
import type { BasePayload } from 'payload'
|
|
|
|
type CreateHealthRouteArgs = {
|
|
/**
|
|
* Collection to ping for a real DB round-trip. Default 'pages'. Pick any
|
|
* collection that always exists in the project.
|
|
*/
|
|
collection?: string
|
|
/**
|
|
* Optional extra checks merged into the body (e.g. a cache or queue ping).
|
|
* Throwing marks the whole healthcheck unhealthy.
|
|
*/
|
|
extra?: () => Promise<Record<string, unknown>>
|
|
/** Same cached accessor the rest of the app uses. */
|
|
getCachedPayload: () => Promise<BasePayload>
|
|
}
|
|
|
|
/**
|
|
* A liveness/readiness route for Coolify/Docker healthchecks and uptime
|
|
* monitors. Does a real DB round-trip (not just "process is up") and returns
|
|
* 200 when reachable, 503 when not — so an orchestrator can restart or hold
|
|
* traffic off a container whose database is down.
|
|
*
|
|
* // app/api/health/route.ts
|
|
* import { createHealthRoute } from '@intecion/ipal-kit'
|
|
* import { getCachedPayload } from '@/lib/content'
|
|
* export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck
|
|
* export const GET = createHealthRoute({ getCachedPayload })
|
|
*
|
|
* Point Coolify's healthcheck at /api/health. Uses the global `Response`
|
|
* (standard in Next route handlers) — no next/server import, peer-dep clean.
|
|
*/
|
|
export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {
|
|
const { collection = 'pages', extra, getCachedPayload } = args
|
|
|
|
return async () => {
|
|
const startedAt = Date.now()
|
|
try {
|
|
const payload = await getCachedPayload()
|
|
// Cheapest real round-trip: ask for at most one row, no population.
|
|
await payload.find({
|
|
collection: collection as never,
|
|
depth: 0,
|
|
limit: 1,
|
|
pagination: false,
|
|
})
|
|
|
|
const extraData = extra ? await extra() : {}
|
|
const body = {
|
|
db: 'up',
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
tookMs: Date.now() - startedAt,
|
|
...extraData,
|
|
}
|
|
return new Response(JSON.stringify(body), {
|
|
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
|
|
status: 200,
|
|
})
|
|
} catch (err) {
|
|
// Log the real error for ops; keep the PUBLIC body generic — a 503 with
|
|
// `db: 'down'` is all an orchestrator needs, and raw DB error text (host,
|
|
// credentials-in-URL, driver internals) must not leak on a public route.
|
|
console.warn('[ipal] createHealthRoute: database unreachable:', err)
|
|
const body = {
|
|
db: 'down',
|
|
status: 'error',
|
|
timestamp: new Date().toISOString(),
|
|
tookMs: Date.now() - startedAt,
|
|
}
|
|
return new Response(JSON.stringify(body), {
|
|
headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },
|
|
status: 503,
|
|
})
|
|
}
|
|
}
|
|
}
|