mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-11-23 02:10:12 +01:00
bbfc455342
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.
41 lines
1.1 KiB
TypeScript
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;
|