NGU-Web/src/lib/api.ts
Zaldimmar 6191322fea Pick up files added to the Blog folder in Drive, and name nginx errors
Opening Tools → Media → Files (or a Choose a file picker) now looks in
the shared drive's Blog folder, at most every 30 seconds, and adds
anything put there in Drive itself: shared as anyone with the link,
previewed, Google Docs, Sheets and Slides included, folders and
shortcuts left out. A file Drive won't share is named in a note and
tried again every ten minutes.

A reply that isn't the API's (nginx's own error page) now says what it
was: a 413 names nginx's upload limit, a 502 the service, a 504 the
timeout, instead of "Server did not return JSON".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 19:14:40 -05:00

120 lines
4.4 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
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<number, string> = {
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 });
}