Refactor fetch with timeout to separate utility

This commit is contained in:
Bill Thornton 2022-03-23 10:13:02 -04:00 committed by Bill Thornton
parent 5606893904
commit aea71d8f23
2 changed files with 29 additions and 18 deletions

20
utils/Fetch.js Normal file
View File

@ -0,0 +1,20 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
export function fetchWithTimeout(url, timeout) {
const abortController = new AbortController();
const { signal } = abortController;
const timeoutId = setTimeout(() => {
console.log('fetch timed out, aborting');
abortController.abort();
}, timeout);
return fetch(url, { signal })
.finally(() => {
clearTimeout(timeoutId);
});
}

View File

@ -6,6 +6,8 @@
import normalizeUrl from 'normalize-url';
import { fetchWithTimeout } from './Fetch';
const TIMEOUT_DURATION = 5000; // timeout request after 5s
export const parseUrl = (host = '', port = '') => {
@ -31,19 +33,8 @@ export const fetchServerInfo = async (server = {}) => {
const infoUrl = `${serverUrl}system/info/public`;
console.log('info url', infoUrl);
// Try to fetch the server's public info
const controller = new AbortController();
const { signal } = controller;
const request = fetch(infoUrl, { signal });
const timeoutId = setTimeout(() => {
console.log('request timed out, aborting');
controller.abort();
}, TIMEOUT_DURATION);
const responseJson = await request.then(response => {
clearTimeout(timeoutId);
const responseJson = await fetchWithTimeout(infoUrl, TIMEOUT_DURATION)
.then(response => {
if (!response.ok) {
throw new Error(`Error response status [${response.status}] received from ${infoUrl}`);
}