UNPKG

smart-api-fetcher

Version:

A smart fetch utility with retries, timeout, and automatic JSON parsing.

63 lines (54 loc) 1.5 kB
// index.js /** * Smart API Fetcher * A wrapper for fetch with: * - Retry mechanism * - Timeout support * - Auto JSON parsing */ async function smartFetch(url, options = {}) { const { retries = 3, timeout = 5000, retryDelay = 1000, fetchOptions = {} } = options; let attempt = 0; const fetchWithTimeout = (url, opts) => { return new Promise((resolve, reject) => { const controller = new AbortController(); const timer = setTimeout(() => { controller.abort(); reject(new Error(`Request timed out after ${timeout}ms`)); }, timeout); fetch(url, { ...opts, signal: controller.signal }) .then(res => { clearTimeout(timer); if (!res.ok) { reject(new Error(`HTTP error! Status: ${res.status}`)); } else { return res.json().then(data => resolve(data)); } }) .catch(err => { clearTimeout(timer); reject(err); }); }); }; while (attempt <= retries) { try { return await fetchWithTimeout(url, fetchOptions); } catch (error) { if (attempt === retries) { throw error; } console.warn( `Attempt ${attempt + 1} failed: ${error.message}. Retrying in ${retryDelay}ms...` ); await new Promise(res => setTimeout(res, retryDelay)); attempt++; } } } module.exports = smartFetch;