helpers/fetch-mixin.js

83 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2022-03-11 23:42:26 +01:00
export const fetchMixin = function(superClass) {
return class extends superClass {
constructor() {
super();
this.__abortControllers = new Map();
}
2023-08-25 15:04:17 +02:00
get(url, overwrite = true) {
return this.do('GET', url, null, overwrite);
2022-03-11 23:42:26 +01:00
}
head(url) {
return fetch(url, { method: 'HEAD' });
}
2023-08-25 15:04:17 +02:00
post(url, data, overwrite = true) {
return this.do('POST', url, data, overwrite);
}
async do(method, url, data, overwrite = true) {
this.__cancelRunningRequest(method, url);
2022-03-11 23:42:26 +01:00
if (overwrite === true) {
const ac = new AbortController();
2023-08-25 15:04:17 +02:00
this.__abortControllers.set(`${method}:${url}`, ac);
2022-03-11 23:42:26 +01:00
}
try {
const reqOptions = {
2023-08-25 15:04:17 +02:00
method,
signal: overwrite ? this.__abortControllers.get(`${method}:${url}`).signal : null,
2022-03-11 23:42:26 +01:00
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
referrer: 'no-referrer',
2023-08-25 15:04:17 +02:00
body: data ? JSON.stringify(data) : undefined
2022-03-11 23:42:26 +01:00
};
document.dispatchEvent(new CustomEvent('before-request', { detail: reqOptions, bubbles: true, composed: true }));
2023-10-05 12:28:51 +02:00
const resp = await fetch(url, reqOptions);
2023-08-25 15:04:17 +02:00
this.__abortControllers.delete(`${method}:${url}`);
2023-10-05 12:28:51 +02:00
if (resp.status === 500) {
console.error(resp);
}
2022-03-11 23:42:26 +01:00
2023-10-05 12:28:51 +02:00
if (resp.status !== 200) {
document.dispatchEvent(new CustomEvent('request-error', { detail: resp, bubbles: true, composed: true }));
2022-03-11 23:42:26 +01:00
}
2023-10-05 12:28:51 +02:00
return await resp.json();
2022-03-11 23:42:26 +01:00
} catch (err) {
if (err.name === 'AbortError') {
return { statusCode: -1, error: err };
} else {
2023-08-25 15:04:17 +02:00
this.__abortControllers.delete(`${method}:${url}`);
2022-03-11 23:42:26 +01:00
return { statusCode: null, error: err };
}
}
}
2023-08-25 15:04:17 +02:00
isInFlight(method, url) {
if (url === undefined) {
console.error('Missing url parameter');
return false;
}
return Boolean(this.__abortControllers.get(`${method}:${url}`));
2022-03-11 23:42:26 +01:00
}
2023-08-25 15:04:17 +02:00
__cancelRunningRequest(method, url) {
if (this.__abortControllers.has(`${method}:${url}`)) {
2022-03-11 23:42:26 +01:00
try {
2023-08-25 15:04:17 +02:00
this.__abortControllers.get(`${method}:${url}`).abort();
2022-03-11 23:42:26 +01:00
} catch (err) { }
2023-08-25 15:04:17 +02:00
this.__abortControllers.delete(`${method}:${url}`);
2022-03-11 23:42:26 +01:00
}
}
};
};