Add api.js module
This commit is contained in:
parent
01a7a4cb59
commit
7f92cc32b7
1 changed files with 30 additions and 0 deletions
30
public/js/api.js
Normal file
30
public/js/api.js
Normal 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');
|
||||
}
|
||||
Loading…
Reference in a new issue