2021-02-04 19:15:23 +01:00
|
|
|
import { memoize } from 'lodash';
|
2021-01-19 17:41:57 +01:00
|
|
|
|
|
|
|
const getFetchWithTimeout = memoize((timeout) => {
|
|
|
|
if (!Number.isInteger(timeout) || timeout < 1) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw new Error('Must specify positive integer timeout.');
|
2021-01-19 17:41:57 +01:00
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
return async function _fetch(url, opts) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const abortController = new window.AbortController();
|
|
|
|
const { signal } = abortController;
|
2020-04-15 19:23:27 +02:00
|
|
|
const f = window.fetch(url, {
|
2019-09-04 22:00:11 +02:00
|
|
|
...opts,
|
2020-12-23 17:15:07 +01:00
|
|
|
signal,
|
2021-02-04 19:15:23 +01:00
|
|
|
});
|
2019-09-04 22:00:11 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
const timer = setTimeout(() => abortController.abort(), timeout);
|
2019-09-04 22:00:11 +02:00
|
|
|
|
|
|
|
try {
|
2021-02-04 19:15:23 +01:00
|
|
|
const res = await f;
|
|
|
|
clearTimeout(timer);
|
|
|
|
return res;
|
2019-09-04 22:00:11 +02:00
|
|
|
} catch (e) {
|
2021-02-04 19:15:23 +01:00
|
|
|
clearTimeout(timer);
|
|
|
|
throw e;
|
2019-09-04 22:00:11 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
|
|
|
});
|
2019-09-04 22:00:11 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
export default getFetchWithTimeout;
|