export async function request(path, options = {}) {
const response = await fetch(`/api${path}`, {
credentials: "same-origin",
...options
});
if (response.status === 401) {
window.dispatchEvent(new CustomEvent("book:unauthenticated"));
throw new Error("unauthorized");
}
if (response.status === 204) return null;
if (!response.ok) {
const text = await response.text();
let detail = text;
try {
const data = JSON.parse(text);
detail = data.detail || data.error || text;
} catch {
/* keep text */
}
throw new Error(`${response.status}: ${detail}`);
}
const contentType = response.headers.get("content-type") || "";
return contentType.includes("application/json")
? response.json()
: response.text();
}
export const apiGet = path => request(path);
export const apiSend = (path, method, body) =>
request(path, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined
});
export const encodePath = path =>
String(path || "")
.split("/")
.map(encodeURIComponent)
.join("/");