secutorpro's picture
fetch client with JWT session
f828f2d verified
Raw History Blame
999 Bytes
let token = sessionStorage.getItem('dc_token') || '';
export function setToken(t) {
token = t || '';
if (token) sessionStorage.setItem('dc_token', token);
else sessionStorage.removeItem('dc_token');
}
export function getToken() { return token; }
async function request(path, options = {}) {
const res = await fetch(`/api${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
if (res.status === 401) {
setToken('');
throw new Error('Session expired — log in again');
}
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error(data?.error || res.statusText);
return data;
}
export const api = {
get: (p) => request(p),
post: (p, body) => request(p, { method: 'POST', body: JSON.stringify(body ?? {}) }),
put: (p, body) => request(p, { method: 'PUT', body: JSON.stringify(body ?? {}) }),
del: (p) => request(p, { method: 'DELETE' }),
};