add fetch polyfill

This commit is contained in:
hippoz 2022-08-05 22:29:20 +03:00
parent f87077d381
commit 4264d9ffac
No known key found for this signature in database
GPG key ID: 7C52899193467641
2 changed files with 32 additions and 2 deletions

View file

@ -1,5 +1,35 @@
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,
@ -24,7 +54,7 @@ export default async function(method, endpoint, auth=true, body=null) {
}
try {
const res = await fetch(endpoint, options);
const res = await compatibleFetch(endpoint, options);
return {
success: true,
json: res.status === 204 ? null : await res.json(),

View file

@ -1,5 +1,5 @@
const defaults = {
"server:apiBase": `${window.location.origin}/api/v1`,
"server:apiBase": `${window.location.origin || ""}/api/v1`,
"server:gatewayBase": `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/gateway`,
"auth:token": "",
"ui:doAnimations": true,