2021-02-04 19:15:23 +01:00
|
|
|
import { memoize } from 'lodash';
|
2022-07-19 18:13:45 +02:00
|
|
|
import { SECOND } from '../constants/time';
|
2021-01-19 17:41:57 +01:00
|
|
|
|
2023-03-31 18:52:33 +02:00
|
|
|
/**
|
|
|
|
* Returns a function that can be used to make an HTTP request but timing out
|
|
|
|
* automatically after a desired amount of time.
|
|
|
|
*
|
|
|
|
* @param timeout - The number of milliseconds to wait until the request times
|
|
|
|
* out.
|
|
|
|
* @returns A function that, when called, returns a promise that either resolves
|
|
|
|
* to the HTTP response object or is rejected if a network error is encountered
|
|
|
|
* or the request times out.
|
|
|
|
*/
|
2022-07-19 18:13:45 +02:00
|
|
|
const getFetchWithTimeout = memoize((timeout = SECOND * 30) => {
|
2021-01-19 17:41:57 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2023-03-31 18:52:33 +02:00
|
|
|
return async function fetchWithTimeout(
|
|
|
|
url: RequestInfo,
|
|
|
|
opts?: RequestInit,
|
|
|
|
): Promise<Response> {
|
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 {
|
2023-03-31 18:52:33 +02:00
|
|
|
return await f;
|
|
|
|
} finally {
|
2021-02-04 19:15:23 +01:00
|
|
|
clearTimeout(timer);
|
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;
|