// src/lib/fetchWithRetry.ts
export async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries = 3,
delay = 1000,
fallback?: () => Promise,
cacheKey?: string
): Promise<Response | any> {
// Cek cache
if (cacheKey) {
const cached = localStorage.getItem(cacheKey);
if (cached) {
try {
return JSON.parse(cached);
} catch {}
}
}
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url, options);
if (response.status !== 503) {
// Simpan ke cache jika perlu
if (cacheKey && response.ok) {
const clone = response.clone();
clone.json().then(data => {
localStorage.setItem(cacheKey, JSON.stringify(data));
});
}
return response;
}
await new Promise(res => setTimeout(res, delay));
} catch (err) {
if (i === retries - 1) {
// Jika ada fallback, gunakan fallback
if (fallback) return fallback();
throw err;
}
await new Promise(res => setTimeout(res, delay));
}
}
if (fallback) return fallback();
throw new Error('Server masih sibuk, silakan coba beberapa saat lagi.');
}