1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-22 09:23:21 +01:00

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.
This commit is contained in:
Elliot Winkler 2023-03-31 10:52:33 -06:00 committed by GitHub
parent 74b9ab28f3
commit bbfc455342
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 6 deletions

View File

@ -1,12 +1,25 @@
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 _fetch(url, opts) {
return async function fetchWithTimeout(
url: RequestInfo,
opts?: RequestInit,
): Promise<Response> {
const abortController = new window.AbortController();
const { signal } = abortController;
const f = window.fetch(url, {
@ -17,12 +30,9 @@ const getFetchWithTimeout = memoize((timeout = SECOND * 30) => {
const timer = setTimeout(() => abortController.abort(), timeout);
try {
const res = await f;
return await f;
} finally {
clearTimeout(timer);
return res;
} catch (e) {
clearTimeout(timer);
throw e;
}
};
});