Add user database migration, core reusable components, and layout structure
This commit is contained in:
+13
-10
@@ -1,26 +1,29 @@
|
||||
import { getToken, clearToken } from './auth.mjs';
|
||||
|
||||
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';
|
||||
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 ? (isForm ? body : JSON.stringify(body)) : undefined,
|
||||
body: body !== undefined
|
||||
? (isFormData ? body : JSON.stringify(body))
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
clearToken();
|
||||
window.dispatchEvent(new CustomEvent('auth:expired'));
|
||||
return null;
|
||||
throw new Error('Session expired');
|
||||
}
|
||||
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
|
||||
if (!res.ok) throw new Error(json.error || `Request failed (${res.status})`);
|
||||
return json.data;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user