import { redirectToLogin } from "./routes"; import type { ApiErrorBody } from "./types"; export class ApiError extends Error { readonly status: number; readonly code: string; constructor(status: number, code: string, message: string) { super(message); this.name = "ApiError"; this.status = status; this.code = code; } } export interface ApiOptions { signal?: AbortSignal; suppressAuthRedirect?: boolean; } async function readBody(response: Response): Promise { const contentType = response.headers.get("content-type") ?? ""; if (contentType.includes("application/json")) { try { return await response.json(); } catch { return null; } } const text = await response.text(); return text ? { error: text, code: "" } : null; } export async function apiRequest( path: string, init: RequestInit = {}, options: ApiOptions = {}, ): Promise { const headers = new Headers(init.headers); headers.set("Accept", "application/json"); if (typeof init.body === "string" && !headers.has("Content-Type")) { headers.set("Content-Type", "application/json"); } let response: Response; try { response = await fetch(path, { ...init, headers, credentials: "same-origin", signal: options.signal, }); } catch (error) { if (error instanceof DOMException && error.name === "AbortError") throw error; throw new ApiError( 0, "network_error", "Could not reach Oolong. Check your connection and try again.", ); } const body = await readBody(response); if (!response.ok) { const envelope = (body ?? {}) as Partial; const code = typeof envelope.code === "string" && envelope.code ? envelope.code : "http_" + response.status; const message = typeof envelope.error === "string" && envelope.error ? envelope.error : "Oolong could not complete that request (" + response.status + ")."; if (response.status === 401 && !options.suppressAuthRedirect) { redirectToLogin(); } throw new ApiError(response.status, code, message); } return body as T; } export function apiGet(path: string, options: ApiOptions = {}): Promise { return apiRequest(path, { method: "GET" }, options); } export function apiSend( method: "POST" | "PUT" | "DELETE", path: string, body?: unknown, options: ApiOptions = {}, ): Promise { return apiRequest( path, { method, body: body === undefined ? undefined : JSON.stringify(body), }, options, ); }