2023-05-28 22:54:17 +00:00
|
|
|
const postHeaders = {
|
|
|
|
mode: 'cors',
|
|
|
|
credentials: 'same-origin',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
function getQuery(data) {
|
|
|
|
if (!data) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return `?${new URLSearchParams(data).toString()}`;
|
|
|
|
}
|
|
|
|
|
2023-06-25 17:52:00 +00:00
|
|
|
async function get(path, query = {}) {
|
2023-06-11 03:32:02 +00:00
|
|
|
const res = await fetch(`/api${path}${getQuery(query)}`);
|
2023-05-28 22:54:17 +00:00
|
|
|
const body = await res.json();
|
|
|
|
|
|
|
|
if (res.ok) {
|
|
|
|
return body;
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(body.message);
|
|
|
|
}
|
|
|
|
|
2023-06-25 17:52:00 +00:00
|
|
|
async function post(path, data, { query } = {}) {
|
2023-06-11 03:32:02 +00:00
|
|
|
const res = await fetch(`/api${path}${getQuery(query)}`, {
|
2023-05-28 22:54:17 +00:00
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify(data),
|
|
|
|
...postHeaders,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (res.status === 204) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const body = await res.json();
|
|
|
|
|
|
|
|
if (res.ok) {
|
|
|
|
return body;
|
|
|
|
}
|
|
|
|
|
2023-06-05 23:30:46 +00:00
|
|
|
throw new Error(body.statusMessage);
|
2023-05-28 22:54:17 +00:00
|
|
|
}
|
|
|
|
|
2023-06-25 17:52:00 +00:00
|
|
|
async function patch(path, data, { query } = {}) {
|
2023-06-11 03:32:02 +00:00
|
|
|
const res = await fetch(`/api${path}${getQuery(query)}`, {
|
2023-05-28 22:54:17 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2023-06-25 17:52:00 +00:00
|
|
|
async function del(path, { data, query } = {}) {
|
2023-06-11 03:32:02 +00:00
|
|
|
const res = await fetch(`/api${path}${getQuery(query)}`, {
|
2023-05-28 22:54:17 +00:00
|
|
|
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);
|
|
|
|
}
|
2023-06-25 17:52:00 +00:00
|
|
|
|
|
|
|
export {
|
|
|
|
get,
|
|
|
|
post,
|
|
|
|
patch,
|
|
|
|
del,
|
2023-06-25 21:50:08 +00:00
|
|
|
del as delete,
|
2023-06-25 17:52:00 +00:00
|
|
|
};
|