Files
rustpad/static/js/api.js
T
2026-07-22 11:03:50 +02:00

20 lines
1.3 KiB
JavaScript

export async function api(path, options = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 12000);
try {
const headers = new Headers(options.headers || {});
if (!(options.body instanceof FormData) && !headers.has("content-type")) headers.set("content-type", "application/json");
const response = await fetch(path, { ...options, headers, signal: controller.signal });
const contentType = response.headers.get("content-type") || "";
const data = contentType.includes("application/json") ? await response.json().catch(() => ({})) : {};
if (!response.ok) {
const defaults = { 400: "Invalid request.", 401: "Authentication required.", 403: "Access denied.", 404: "The requested resource was not found.", 405: "This operation is not allowed.", 409: "The requested change conflicts with existing data.", 413: "The uploaded data is too large.", 429: "Too many requests. Try again later.", 500: "Server error. Try again later.", 503: "Service temporarily unavailable." };
throw new Error(data.error || defaults[response.status] || `Request failed (${response.status}).`);
}
return data;
} catch (error) {
if (error.name === "AbortError") throw new Error("Timed out");
throw error;
} finally { clearTimeout(timeout); }
}