Skip to content

i get eror 503 on web server and done after update src/lib and add fetchWithRetry.ts #46

@myspace253

Description

@myspace253

// 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.');
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions