chore: add timeout mechanism for fetch calls (#3649)
This commit is contained in:
@ -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,
|
||||
};
|
||||
|
Reference in New Issue
Block a user