Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor fetch with timeout to separate utility #353

Merged
merged 2 commits into from
Mar 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions jest.setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@
import { enableFetchMocks } from 'jest-fetch-mock';
import { AbortController } from 'node-abort-controller';

// DOMException is not polyfilled in released version of jest-fetch-mock
// refs: https:/jefflau/jest-fetch-mock/pull/160
if (typeof DOMException === 'undefined') {
global.DOMException = require('domexception');
}

global.AbortController = AbortController;

enableFetchMocks();
Expand Down
31 changes: 24 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
"@types/jest": "^27.0.2",
"@typescript-eslint/parser": "^4.9.1",
"babel-preset-expo": "8.5.1",
"domexception": "^4.0.0",
"eslint": "^7.4.0",
"eslint-plugin-compat": "^3.9.0",
"eslint-plugin-eslint-comments": "^3.1.2",
Expand Down
20 changes: 20 additions & 0 deletions utils/Fetch.js
Original file line number Diff line number Diff line change
@@ -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);
});
}
27 changes: 9 additions & 18 deletions utils/ServerValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '') => {
Expand All @@ -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;
Expand Down
32 changes: 32 additions & 0 deletions utils/__tests__/Fetch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* 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/.
*/

import { fetchWithTimeout } from '../Fetch';

describe('Fetch', () => {
beforeEach(() => {
fetch.resetMocks();
jest.clearAllMocks();
});

afterEach(() => {
jest.useRealTimers();
});

describe('fetchWithTimeout()', () => {
it('should throw an error when duration passes', async () => {
jest.useFakeTimers();
fetch.mockResponse(() => {
jest.runAllTimers();
return Promise.resolve('');
});

await expect(fetchWithTimeout('http://example.com', 100))
.rejects
.toThrow('The operation was aborted. ');
});
});
});