api.js
js1 kB27 linesIn assignment_1_solution.zip
assignment_1_solution.zipfrontendsrcapi.js
// Tiny fetch wrapper. All calls use relative URLs (/api/...), so the same
// build works behind Vite (dev), nginx (Docker) and on EC2 without changes.
const TOKEN_KEY = "campus-events-token";
export const tokenStore = {
get: () => localStorage.getItem(TOKEN_KEY),
set: (t) => localStorage.setItem(TOKEN_KEY, t),
clear: () => localStorage.removeItem(TOKEN_KEY),
};
export async function api(path, { method = "GET", body } = {}) {
const headers = { "Content-Type": "application/json" };
const token = tokenStore.get();
if (token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(`/api${path}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 204) return null;
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error ?? `Request failed (${res.status})`);
return data;
}