mirror of
https://github.com/jellyfin/jellyfin-expo.git
synced 2024-11-23 05:59:39 +00:00
Refactor fetch with timeout to separate utility
This commit is contained in:
parent
5606893904
commit
aea71d8f23
20
utils/Fetch.js
Normal file
20
utils/Fetch.js
Normal 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);
|
||||
});
|
||||
}
|
@ -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}`);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user