1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-29 23:58:06 +01:00
metamask-extension/shared/modules/fetch-with-timeout.ts
Elliot Winkler bbfc455342
Convert shared/modules/fetch-with-timeout to TS (#18351)
We want to convert NetworkController to TypeScript in order to be able
to compare differences in the controller between in this repo and the
core repo. To do this, however, we need to convert the dependencies of
the controller to TypeScript.

As a part of this effort, this commit converts
`shared/modules/fetch-with-timeout.js` to TypeScript.
2023-03-31 10:52:33 -06:00

41 lines
1.1 KiB
TypeScript

import { memoize } from 'lodash';
import { SECOND } from '../constants/time';
/**
* 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.
*/
const getFetchWithTimeout = memoize((timeout = SECOND * 30) => {
if (!Number.isInteger(timeout) || timeout < 1) {
throw new Error('Must specify positive integer timeout.');
}
return async function fetchWithTimeout(
url: RequestInfo,
opts?: RequestInit,
): Promise<Response> {
const abortController = new window.AbortController();
const { signal } = abortController;
const f = window.fetch(url, {
...opts,
signal,
});
const timer = setTimeout(() => abortController.abort(), timeout);
try {
return await f;
} finally {
clearTimeout(timer);
}
};
});
export default getFetchWithTimeout;