From aea71d8f23f4671a8d0a032e412c3025fbf61cba Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Wed, 23 Mar 2022 10:13:02 -0400 Subject: [PATCH] Refactor fetch with timeout to separate utility --- utils/Fetch.js | 20 ++++++++++++++++++++ utils/ServerValidator.js | 27 +++++++++------------------ 2 files changed, 29 insertions(+), 18 deletions(-) create mode 100644 utils/Fetch.js diff --git a/utils/Fetch.js b/utils/Fetch.js new file mode 100644 index 0000000..d786895 --- /dev/null +++ b/utils/Fetch.js @@ -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); + }); +} diff --git a/utils/ServerValidator.js b/utils/ServerValidator.js index eb43564..0e50f39 100644 --- a/utils/ServerValidator.js +++ b/utils/ServerValidator.js @@ -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,24 +33,13 @@ 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); - if (!response.ok) { - throw new Error(`Error response status [${response.status}] received from ${infoUrl}`); - } - return response.json(); - }); + const responseJson = await fetchWithTimeout(infoUrl, TIMEOUT_DURATION) + .then(response => { + if (!response.ok) { + throw new Error(`Error response status [${response.status}] received from ${infoUrl}`); + } + return response.json(); + }); console.log('response', responseJson); return responseJson;