waffle/frontend/src/request.js

43 lines
972 B
JavaScript
Raw Normal View History

2022-05-05 16:31:10 +03:00
import { getItem } 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) {
2022-05-05 16:31:10 +03:00
const token = getItem("token");
if (token) {
options.headers = {
...options.headers || {},
"Authorization": `Bearer ${token}`
};
}
}
try {
const res = await fetch(endpoint, options);
return {
success: true,
2022-04-26 23:57:06 +03:00
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
}
}
}