Files
readest/apps/readest-app/src/utils/fetch.ts
T
Huang Xin 2dcb5d7c1e sync: add network timeout of sync to 5 sec (#1432)
* sync: add network timeout of sync to 5 sec

* css: minor tweaks on headings and list
2025-06-20 16:45:10 +02:00

33 lines
899 B
TypeScript

import { getAccessToken } from './access';
export const fetchWithTimeout = (url: string, options: RequestInit, timeout = 8000) => {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
return fetch(url, {
...options,
signal: controller.signal,
}).finally(() => clearTimeout(id));
};
export const fetchWithAuth = async (url: string, options: RequestInit) => {
const token = await getAccessToken();
if (!token) {
throw new Error('Not authenticated');
}
const headers = {
...options.headers,
Authorization: `Bearer ${token}`,
};
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
const errorData = await response.json();
console.error('Error:', errorData.error || response.statusText);
throw new Error(errorData.error || 'Request failed');
}
return response;
};