SPB Git

Repository Public

client-api.ts 2.0 KB 35 lines typescript

1"use client";23export class ApiClientError extends Error {4  constructor(public status: number, public code: string, message: string, public details?: unknown) { super(message); }5}67let csrf: string | null = null;8export const setCsrf = (t: string | null) => { csrf = t; };910/** JSON fetch against our own API. Sends the CSRF header; network failures surface as code "network". */11export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown; form?: FormData; signal?: AbortSignal } = {}): Promise<T> {12  let res: Response;13  try {14    res = await fetch(path, {15      method: init.method ?? (init.body !== undefined || init.form ? "POST" : "GET"),16      headers: { ...(init.body !== undefined ? { "Content-Type": "application/json" } : {}), ...(csrf ? { "X-CSRF-Token": csrf } : {}) },17      body: init.form ?? (init.body !== undefined ? JSON.stringify(init.body) : undefined),18      credentials: "same-origin", cache: "no-store", signal: init.signal,19    });20  } catch (e) { if ((e as Error).name === "AbortError") throw e; throw new ApiClientError(0, "network", "Network error"); }21  const text = await res.text();22  let data: unknown = null;23  try { data = text ? JSON.parse(text) : null; } catch { /* not JSON */ }24  if (!res.ok) {25    // The session ended (expired or revoked elsewhere): back to the sign-in page, keeping where we were.26    if (res.status === 401 && !path.startsWith("/api/auth/") && typeof window !== "undefined" && !window.location.pathname.startsWith("/admin/login")) window.location.assign(`/admin/login?next=${encodeURIComponent(window.location.pathname)}`);27    const e = (data as { error?: { code?: string; message?: string; details?: unknown } } | null)?.error;28    throw new ApiClientError(res.status, e?.code ?? "http_" + res.status, e?.message ?? `HTTP ${res.status}`, e?.details);29  }30  return data as T;31}3233/** One key per user action: a retried request returns the job that already exists. */34export const idempotencyKey = () => crypto.randomUUID();35
Files main
Menu

Theme