57 lines
1.2 KiB
JavaScript
57 lines
1.2 KiB
JavaScript
function getHeaders() {
|
|
const headers = new Headers();
|
|
headers.append("Accept", "application/json");
|
|
headers.append("Content-Type", "application/json");
|
|
return headers;
|
|
}
|
|
|
|
function internalFetch(url, options) {
|
|
return fetch(url, options).then((res) =>
|
|
res.text().then((text) => {
|
|
let t = text ? JSON.parse(text) : res.statusText;
|
|
if (!res.ok) {
|
|
if (res.status === 404) throw new Error(t || "Not found");
|
|
|
|
if (res.status >= 400 && res.status < 600 && t) throw t;
|
|
|
|
throw new Error(t || "Unknown error");
|
|
}
|
|
return t;
|
|
})
|
|
);
|
|
}
|
|
|
|
export function post(url, body) {
|
|
const options = {
|
|
method: "POST",
|
|
body: JSON.stringify(body),
|
|
headers: getHeaders()
|
|
};
|
|
return internalFetch(url, options);
|
|
}
|
|
|
|
export function put(url, body) {
|
|
const options = {
|
|
method: "PUT",
|
|
body: JSON.stringify(body),
|
|
headers: getHeaders()
|
|
};
|
|
return internalFetch(url, options);
|
|
}
|
|
|
|
export function get(url) {
|
|
const options = {
|
|
method: "GET",
|
|
headers: getHeaders()
|
|
};
|
|
return internalFetch(url, options);
|
|
}
|
|
|
|
export function del(url) {
|
|
const options = {
|
|
method: "DELETE",
|
|
headers: getHeaders()
|
|
};
|
|
return internalFetch(url, options);
|
|
}
|