/* ═══════════════════════════════════════════════════════════════ API CLIENT One place that knows how to talk to the server, so components never call fetch directly. The cache is a module-level Map of in-flight and settled promises. Two components asking for /events during the same render pass share one request, and a remount inside the TTL costs nothing. It resets on page load, which is the right lifetime for content that changes weekly. A failure isn't cached, and surfaces as an error rather than empty data. ═══════════════════════════════════════════════════════════════ */ const BASE = import.meta.env?.VITE_API_BASE ?? "/api"; const DEFAULT_TTL = 60_000; const cache = new Map(); // path → { at, promise } export class ApiError extends Error { status; fields; constructor(message, { status, fields }: { status?: number; fields?: any } = {}) { super(message); this.name = "ApiError"; this.status = status; this.fields = fields; } } /* nginx's answers of its own, in words that point at the fix. */ const NOT_THE_API: Record = { 413: "Too large for the web server: nginx's upload limit for this address is lower than the file (HTTP 413). The nginx block for it is in the docs.", 502: "The API isn't answering (HTTP 502). Check that the ngu-api service is running.", 504: "The API took too long to answer (HTTP 504). Try again; if it keeps happening, nginx's timeout for this address is too short.", }; async function request(path, options: RequestInit = {}) { const response = await fetch(`${BASE}${path}`, { ...options, headers: { Accept: "application/json", ...options.headers }, }); if (response.status === 204) return null; const type = response.headers.get("content-type") ?? ""; if (!type.includes("application/json")) { // Not the API's answer: the SPA fallback returning index.html for // a URL the API doesn't serve, or nginx's own error page when the // request never reached the API (nothing in its journal then). // Parsing it would throw something useless; say what it was. throw new ApiError(NOT_THE_API[response.status] ?? `The server didn't answer as expected (HTTP ${response.status}).`, { status: response.status, }); } const body = await response.json(); if (!response.ok) { throw new ApiError(body.error ?? "Request failed.", { status: response.status, fields: body.fields, }); } return body; } /* ── Reads ───────────────────────────────────────────────────── get("/events") → cached for 60s get("/events", { ttl: 0 }) → always fresh ───────────────────────────────────────────────────────────── */ export function get(path, { ttl = DEFAULT_TTL }: { ttl?: number } = {}) { const hit = cache.get(path); if (hit && Date.now() - hit.at < ttl) return hit.promise; const promise = request(path).catch((err) => { cache.delete(path); // a failure shouldn't be cached throw err; }); cache.set(path, { at: Date.now(), promise }); return promise; } export function invalidate(path) { if (path) cache.delete(path); else cache.clear(); } /* ── Writes ──────────────────────────────────────────────────── */ export function post(path, data) { return request(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); } export function patch(path, data) { return request(path, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); } export function del(path) { return request(path, { method: "DELETE" }); } /* A multipart body. No Content-Type here: the browser sets it, boundary included, from the FormData itself. */ export function upload(path, form: FormData) { return request(path, { method: "POST", body: form }); }