34 lines
1015 B
JavaScript
34 lines
1015 B
JavaScript
const BASE = '/api';
|
|
let _token = '';
|
|
|
|
export function setToken(t) { _token = t; }
|
|
export function getToken() { return _token; }
|
|
|
|
async function request(method, path, body, isForm = false) {
|
|
const headers = { Authorization: `Bearer ${_token}` };
|
|
if (!isForm && body) headers['Content-Type'] = 'application/json';
|
|
|
|
const res = await fetch(BASE + path, {
|
|
method,
|
|
headers,
|
|
body: body ? (isForm ? body : JSON.stringify(body)) : undefined,
|
|
});
|
|
|
|
if (res.status === 401) {
|
|
window.dispatchEvent(new CustomEvent('auth:expired'));
|
|
return null;
|
|
}
|
|
|
|
const json = await res.json().catch(() => ({}));
|
|
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
|
|
return json.data;
|
|
}
|
|
|
|
export const api = {
|
|
get: (path) => request('GET', path),
|
|
post: (path, body) => request('POST', path, body),
|
|
put: (path, body) => request('PUT', path, body),
|
|
delete: (path) => request('DELETE', path),
|
|
upload: (path, form) => request('POST', path, form, true),
|
|
};
|