Wrapper para fetch com suporte a timeout configurável e retentativas automáticas.
async function fetchComTimeout(url, opcoes = {}, tentativas = 3, timeoutMs = 5000) {
for (let i = 0; i < tentativas; i++) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const resposta = await fetch(url, { ...opcoes, signal: controller.signal });
clearTimeout(timeout);
if (!resposta.ok) throw new Error(`HTTP ${resposta.status}`);
return await resposta.json();
} catch (erro) {
clearTimeout(timeout);
if (i === tentativas - 1) throw erro;
await new Promise(r => setTimeout(r, 500 * (i + 1))); // backoff
}
}
}
// Uso:
const dados = await fetchComTimeout('/api/produtos', { method: 'GET' });