/** * Calls to the backend from the browser (same address, under /api). Errors come back as * { error: { code, message, fields? } }; `call` returns them instead of throwing. */ export type ApiError = { code: string; message: string; fields?: Record }; export type ApiResult = { ok: true; status: number; data: T } | { ok: false; status: number; error: ApiError }; export async function call>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: unknown): Promise> { let res: Response; try { res = await fetch(`/api/v2${path}`, { method, credentials: "same-origin", headers: body !== undefined ? { "Content-Type": "application/json" } : undefined, body: body !== undefined ? JSON.stringify(body) : undefined, }); } catch { return { ok: false, status: 0, error: { code: "OFFLINE", message: "We couldn't reach the server. Check your connection and try again." } }; } const json = (await res.json().catch(() => ({}))) as { error?: ApiError }; if (!res.ok) return { ok: false, status: res.status, error: json.error ?? { code: "ERROR", message: "Something went wrong. Please try again." } }; return { ok: true, status: res.status, data: json as T }; } /** Where to sign in to Accounts' own pages, coming back to `returnTo`. */ export const selfSignIn = (returnTo: string, extra = "") => `/api/self/signin?returnTo=${encodeURIComponent(returnTo)}${extra}`;