Files

37 lines
1.1 KiB
JavaScript

import { getToken, clearToken } from './auth.mjs';
const BASE = '/api';
async function request(method, path, body, isFormData = false) {
const token = getToken();
const headers = {};
if (token) headers['Authorization'] = `Bearer ${token}`;
if (!isFormData && body !== undefined) headers['Content-Type'] = 'application/json';
const res = await fetch(BASE + path, {
method,
headers,
body: body !== undefined
? (isFormData ? body : JSON.stringify(body))
: undefined,
});
if (res.status === 401) {
clearToken();
window.dispatchEvent(new CustomEvent('auth:expired'));
throw new Error('Session expired');
}
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(json.error || `Request failed (${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),
};