helpers/fetch-mixin.js

81 lines
2.2 KiB
JavaScript
Raw 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 }));
const result = await fetch(url, reqOptions).then(response => response.json());
2023-08-25 15:04:17 +02:00
this.__abortControllers.delete(`${method}:${url}`);
2022-03-11 23:42:26 +01:00
if (result.statusCode === 500) {
console.error(result);
}
return result;
} 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
}
}
};
};