45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { checkDatabaseHealth } from "@/lib/db";
|
|
import { ErrorCode, ok, withErrorHandling } from "@/lib/api/response";
|
|
|
|
/**
|
|
* GET /api/health —— 健康检查
|
|
*
|
|
* 用于部署后的可用性探测与监控。返回:
|
|
* - status: "ok" | "degraded"
|
|
* - database: 连通性与往返延迟
|
|
* - timestamp: 服务端时间
|
|
*
|
|
* 数据库不可用时返回 503,便于负载均衡/监控直接判定为不健康。
|
|
*/
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export const GET = withErrorHandling(async () => {
|
|
const database = await checkDatabaseHealth();
|
|
|
|
const payload = {
|
|
status: database.ok ? ("ok" as const) : ("degraded" as const),
|
|
database: {
|
|
ok: database.ok,
|
|
latencyMs: database.latencyMs,
|
|
...(database.error ? { error: database.error } : {}),
|
|
},
|
|
timestamp: new Date().toISOString(),
|
|
};
|
|
|
|
if (!database.ok) {
|
|
return NextResponse.json(
|
|
{
|
|
error: {
|
|
code: ErrorCode.SERVICE_UNAVAILABLE,
|
|
message: "数据库不可用",
|
|
},
|
|
...payload,
|
|
},
|
|
{ status: 503 },
|
|
);
|
|
}
|
|
|
|
return ok(payload);
|
|
});
|