waffle/frontend/src/request.js
2022-04-26 23:57:06 +03:00

42 lines
975 B
JavaScript

import { getAuthToken } from "./storage";
export default async function(method, endpoint, auth=true, body=null) {
const options = {
method,
};
if (body) {
options.body = JSON.stringify(body);
options.headers = {
...options.headers || {},
"Content-Type": "application/json"
};
}
if (auth) {
const token = getAuthToken();
if (token) {
options.headers = {
...options.headers || {},
"Authorization": `Bearer ${token}`
};
}
}
try {
const res = await fetch(endpoint, options);
return {
success: true,
json: res.status === 204 ? null : await res.json(),
ok: res.ok,
status: res.status
}
} catch (e) {
return {
success: false,
json: null,
ok: false,
status: null
}
}
}