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'); }