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;