67 lines
1.9 KiB
TypeScript
67 lines
1.9 KiB
TypeScript
import type { OptimizerDataCache } from "./cache";
|
|
|
|
export function createRequestHandler(cache: OptimizerDataCache) {
|
|
return (request: Request): Response => {
|
|
if (request.method !== "GET") {
|
|
return jsonResponse({ error: "Method not allowed" }, 405, {
|
|
Allow: "GET",
|
|
});
|
|
}
|
|
|
|
const path = new URL(request.url).pathname.replace(/\/+$/, "") || "/";
|
|
if (path === "/health") {
|
|
const payload = cache.getPayload();
|
|
return jsonResponse(
|
|
payload
|
|
? {
|
|
status: payload.status,
|
|
fetchedAt: payload.fetchedAt,
|
|
nextRefreshAt: payload.nextRefreshAt,
|
|
optimizerCount: payload.optimizerCount,
|
|
failedOptimizerCount: payload.failedOptimizerCount,
|
|
...(payload.lastError ? { lastError: payload.lastError } : {}),
|
|
}
|
|
: {
|
|
status: cache.getLastError() ? "error" : "starting",
|
|
...(cache.getLastError()
|
|
? { lastError: cache.getLastError() }
|
|
: {}),
|
|
},
|
|
payload ? 200 : 503,
|
|
);
|
|
}
|
|
|
|
if (path === "/" || path === "/api/optimizers") {
|
|
const payload = cache.getPayload();
|
|
return payload
|
|
? jsonResponse(payload)
|
|
: jsonResponse(
|
|
{
|
|
status: cache.getLastError() ? "error" : "starting",
|
|
message: "No optimizer data is available yet",
|
|
...(cache.getLastError()
|
|
? { lastError: cache.getLastError() }
|
|
: {}),
|
|
},
|
|
503,
|
|
);
|
|
}
|
|
|
|
return jsonResponse({ error: "Not found" }, 404);
|
|
};
|
|
}
|
|
|
|
function jsonResponse(
|
|
value: unknown,
|
|
status = 200,
|
|
additionalHeaders: Record<string, string> = {},
|
|
): Response {
|
|
return Response.json(value, {
|
|
status,
|
|
headers: {
|
|
"Cache-Control": "no-store",
|
|
...additionalHeaders,
|
|
},
|
|
});
|
|
}
|