fix: clear fetch timeout on successful response (#3768)

This commit is contained in:
Erez Rokah 2020-05-17 14:09:06 +03:00 committed by GitHub
parent 6042383b9d
commit 088b1a8ab6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,25 +3,31 @@ import curry from 'lodash/curry';
import flow from 'lodash/flow'; import flow from 'lodash/flow';
import isString from 'lodash/isString'; import isString from 'lodash/isString';
let controller; const isAbortControllerSupported = () => {
let signal; if (typeof window !== 'undefined') {
if (typeof window !== 'undefined') { return !!window.AbortController;
controller = window.AbortController && new AbortController(); }
signal = controller && controller.signal; return false;
} };
const timeout = 60; const timeout = 60;
const fetchWithTimeout = (input, init) => { const fetchWithTimeout = (input, init) => {
if (controller && signal && !init.signal) { if (init.signal || !isAbortControllerSupported()) {
setTimeout(() => controller.abort(), timeout * 1000); return fetch(input, init);
return fetch(input, { ...init, signal }).catch(e => { }
if (e.name === 'AbortError') { const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout * 1000);
return fetch(input, { ...init, signal: controller.signal })
.then(res => {
clearTimeout(timeoutId);
return res;
})
.catch(e => {
if (e.name === 'AbortError' || e.name === 'DOMException') {
throw new Error(`Request timed out after ${timeout} seconds`); throw new Error(`Request timed out after ${timeout} seconds`);
} }
throw e; throw e;
}); });
}
return fetch(input, init);
}; };
const decodeParams = paramsString => const decodeParams = paramsString =>