Files
roast_command_center/public/js/api.js
T
snowspeeder 59645e59b5 Add green-bean inventory and cupping features
Ports inventory management and SCA-style cupping scoring from
hope_roaster: lot tracking with audit-logged consumption, cupping
sessions with server-authoritative scoring and a live radar chart,
and links from the planner (draw-from-lot, open-cupping-session).

Also fixes the Blend/Single-origin toggle layout, replaces tooltips
with an in-context "why" teaching layer, and stages the planner UI
into pre-roast vs. post-roast phases.
2026-07-30 14:47:15 -04:00

36 lines
1.3 KiB
JavaScript

export const csrfToken = () =>
document.cookie
.split("; ")
.find((v) => v.startsWith("rp_csrf="))
?.split("=")[1] || "";
export const protectedFetch = (url, options = {}) =>
fetch(url, {
...options,
headers: { ...options.headers, "x-csrf-token": csrfToken() },
});
export async function api(url, options = {}) {
const response = await protectedFetch(url, {
...options,
headers: { "content-type": "application/json", ...options.headers },
});
const body = await response.json().catch(() => ({}));
if (response.status === 401 && body.code === "unauthorized") {
// This is specifically requireAuth's code for "no valid session" — the session expired
// or was revoked mid-page (account/admin pages otherwise show a permanent "could not
// load" error with no indication the user was signed out). A 401 with any other code
// (e.g. a wrong current password on an account form) is a normal request failure, not a
// sign-out, and must not redirect the user away mid-form.
location.assign("/login");
return new Promise(() => {}); // navigation is already underway; never resolve
}
if (!response.ok) {
const error = new Error(body.error || body.code || "request_failed");
error.code = body.code;
error.status = response.status;
throw error;
}
return body;
}