28 lines
809 B
JavaScript
28 lines
809 B
JavaScript
window.api = {
|
|
async get(path) {
|
|
const r = await fetch(path);
|
|
if (!r.ok) {
|
|
let msg = `HTTP ${r.status}`;
|
|
try { const j = await r.json(); msg = j.error || msg; } catch {}
|
|
throw new Error(msg);
|
|
}
|
|
return r.json();
|
|
},
|
|
async send(method, path, body) {
|
|
const r = await fetch(path, {
|
|
method,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: body ? JSON.stringify(body) : undefined
|
|
});
|
|
if (!r.ok) {
|
|
let msg = `HTTP ${r.status}`;
|
|
try { const j = await r.json(); msg = j.error || msg; } catch {}
|
|
throw new Error(msg);
|
|
}
|
|
return r.json();
|
|
},
|
|
post(path, body) { return this.send('POST', path, body); },
|
|
put(path, body) { return this.send('PUT', path, body); },
|
|
del(path) { return this.send('DELETE', path); }
|
|
};
|