Spaces:
Paused
Paused
File size: 951 Bytes
f828f2d f1f70b6 f828f2d f1f70b6 f828f2d f1f70b6 f828f2d f1f70b6 f828f2d f1f70b6 f828f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | let token = sessionStorage.getItem('dc_token') || '';
export function setToken(t) {
token = t || '';
if (t) sessionStorage.setItem('dc_token', t);
else sessionStorage.removeItem('dc_token');
}
export function getToken() {
return token;
}
async function request(path, opts = {}) {
const res = await fetch('/api' + path, {
...opts,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(opts.headers || {}),
},
});
if (res.status === 401) setToken('');
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' }),
}; |