chore: add timeout mechanism for fetch calls (#3649)

This commit is contained in:
Kunal Kundu
2020-05-12 19:21:13 +05:30
committed by GitHub
parent 334304ed52
commit 3e34e52440
11 changed files with 66 additions and 28 deletions

View File

@ -3,6 +3,27 @@ import curry from 'lodash/curry';
import flow from 'lodash/flow';
import isString from 'lodash/isString';
let controller;
let signal;
if (typeof window !== 'undefined') {
controller = window.AbortController && new AbortController();
signal = controller && controller.signal;
}
const timeout = 60;
const fetchWithTimeout = (input, init) => {
if (controller && signal && !init.signal) {
setTimeout(() => controller.abort(), timeout * 1000);
return fetch(input, { ...init, signal }).catch(e => {
if (e.name === 'AbortError') {
throw new Error(`Request timed out after ${timeout} seconds`);
}
throw e;
});
}
return fetch(input, init);
};
const decodeParams = paramsString =>
List(paramsString.split('&'))
.map(s => List(s.split('=')).map(decodeURIComponent))
@ -51,7 +72,7 @@ const ensureRequestArg2 = func => (arg, req) => func(arg, maybeRequestArg(req));
// This actually performs the built request object
const performRequest = ensureRequestArg(req => {
const args = toFetchArguments(req);
return fetch(...args);
return fetchWithTimeout(...args);
});
// Each of the following functions takes options and returns another
@ -91,4 +112,5 @@ export default {
withParams,
withRoot,
withNoCache,
fetchWithTimeout,
};