Add api.js module

This commit is contained in:
Simon Kühn 2026-05-08 11:38:43 +02:00
parent 01a7a4cb59
commit 7f92cc32b7

30
public/js/api.js Normal file
View file

@ -0,0 +1,30 @@
let _apiPending = 0;
function _apiBar() {
document.getElementById('api-bar').classList.toggle('loading', _apiPending > 0);
}
export function api(method, path, body) {
const opts = { method, credentials: 'include', headers: { 'Content-Type': 'application/json' } };
if (body) opts.body = JSON.stringify(body);
_apiPending++; _apiBar();
return fetch('api/' + path, opts)
.then(res => res.json().then(data => {
if (!res.ok) { const e = new Error(data.error || 'Fehler'); e.status = res.status; throw e; }
return data;
}).catch(e => {
if (e.status) throw e;
const ne = new Error('Fehler'); ne.status = res.status; throw ne;
}))
.catch(e => {
if (e.status === 401 && path !== 'login') {
document.dispatchEvent(new CustomEvent('session-expired'));
}
throw e;
})
.finally(() => { _apiPending--; _apiBar(); });
}
export function loadGoals() {
return api('GET', 'goals');
}