Switch to Svelte
This commit is contained in:
23
frontend/src/lib/api.js
Normal file
23
frontend/src/lib/api.js
Normal file
@@ -0,0 +1,23 @@
|
||||
export async function apiRequest(endpoint, method = 'GET', data = null) {
|
||||
const options = {
|
||||
method,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
if (data) {
|
||||
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
options.body = new URLSearchParams(data).toString();
|
||||
}
|
||||
|
||||
const res = await fetch(`/api${endpoint}`, options);
|
||||
if (!res.ok) {
|
||||
let msg = res.statusText;
|
||||
try {
|
||||
const errBody = await res.json();
|
||||
if (errBody.error) msg = errBody.error;
|
||||
else if (errBody.detail) msg = errBody.detail;
|
||||
} catch(e) {}
|
||||
throw new Error(msg);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
Reference in New Issue
Block a user