waffle/frontend/src/request.js
2022-08-05 22:29:20 +03:00

72 lines
1.9 KiB
JavaScript

import { getItem } from "./storage";
export function compatibleFetch(endpoint, options) {
if (window.fetch && typeof window.fetch === "function") {
return fetch(endpoint, options);
} else {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.addEventListener("load", () => {
resolve({
status: req.status,
ok: [200, 201, 204].includes(req.status),
json() {
return JSON.parse(req.responseText);
}
});
});
req.addEventListener("error", (e) => {
reject(e);
});
req.open(options.method || "GET", endpoint);
if (options.headers) {
for (const [header, value] of Object.entries(options.headers)) {
req.setRequestHeader(header, value);
}
}
req.send(options.body);
});
}
}
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 = getItem("auth:token");
if (token) {
options.headers = {
...options.headers || {},
"Authorization": `Bearer ${token}`
};
}
}
try {
const res = await compatibleFetch(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
}
}
}