Something went wrong. Try again.
Tea journaling on ATProto (alpha) forked from arabica.social/arabica
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import { 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<unknown> { 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<T>( path: string, init: RequestInit = {}, options: ApiOptions = {},): Promise<T> { 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<ApiErrorBody>; 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<T>(path: string, options: ApiOptions = {}): Promise<T> { return apiRequest<T>(path, { method: "GET" }, options);}
export function apiSend<T>( method: "POST" | "PUT" | "DELETE", path: string, body?: unknown, options: ApiOptions = {},): Promise<T> { return apiRequest<T>( path, { method, body: body === undefined ? undefined : JSON.stringify(body), }, options, );}