import { backendBaseUrl as BASE, joinBackendPath } from "./runtime-config"; /** * Error thrown for non-2xx responses. `.message` stays " " for * backward compatibility; `.status` and `.payload` (parsed JSON body, if any) * let callers branch on a specific failure — e.g. a `code: "dwh_unreachable"`. */ export class ApiError extends Error { constructor(readonly status: number, readonly bodyText: string, readonly payload: unknown) { super(`${status} ${bodyText}`); this.name = "ApiError"; } } export async function apiFetch(path: string, init?: RequestInit): Promise { // Only declare a JSON content-type when we actually send a body. Body-less // POSTs (resume, close) would otherwise make Fastify reject the empty body // with FST_ERR_CTP_EMPTY_JSON_BODY (400). const headers: Record = { ...(init?.headers as Record | undefined), }; if (init?.body != null && !("content-type" in headers) && !("Content-Type" in headers)) { headers["content-type"] = "application/json"; } const res = await fetch(joinBackendPath(BASE, path), { ...init, headers }); if (!res.ok) { const bodyText = await res.text().catch(() => ""); let payload: unknown; try { payload = bodyText ? JSON.parse(bodyText) : undefined; } catch { payload = undefined; } throw new ApiError(res.status, bodyText, payload); } if (res.status === 204) return undefined as T; // Accepted fire-and-forget endpoints may legitimately return 202 with no // representation. Keep apiFetch useful for both 202 and 204 contracts. const body = await res.text(); return body ? (JSON.parse(body) as T) : (undefined as T); } export { BASE };