shack/assets/js/api.js

95 lines
1.5 KiB
JavaScript

const postHeaders = {
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
};
function getQuery(data) {
if (!data) {
return '';
}
return `?${new URLSearchParams(data).toString()}`;
}
async function get(path, query = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`);
const body = await res.json();
if (res.ok) {
return body;
}
throw new Error(body.message);
}
async function post(path, data, { query } = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`, {
method: 'POST',
body: JSON.stringify(data),
...postHeaders,
});
if (res.status === 204) {
return null;
}
const body = await res.json();
if (res.ok) {
return body;
}
throw new Error(body.statusMessage);
}
async function patch(path, data, { query } = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`, {
method: 'PATCH',
body: JSON.stringify(data),
...postHeaders,
});
if (res.status === 204) {
return null;
}
const body = await res.json();
if (res.ok) {
return body;
}
throw new Error(body.message);
}
async function del(path, { data, query } = {}) {
const res = await fetch(`/api${path}${getQuery(query)}`, {
method: 'DELETE',
body: JSON.stringify(data),
...postHeaders,
});
if (res.status === 204) {
return null;
}
const body = await res.json();
if (res.ok) {
return body;
}
throw new Error(body.message);
}
export {
get,
post,
patch,
del,
del as delete,
};