async function makeRequestWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
if (attempt === maxRetries) {
throw new Error("Rate limit exceeded after maximum retries");
}
// Exponential backoff with jitter
const baseDelay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
const jitter = Math.random() * 1000; // 0-1s random jitter
const delay = baseDelay + jitter;
console.log(`Rate limited. Retrying in ${delay}ms...`);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
return response;
} catch (error) {
if (attempt === maxRetries) throw error;
}
}
}
// Usage
const response = await makeRequestWithRetry("https://api.us.firstquadrant.ai/v5/contacts", {
headers: {
Authorization: "Bearer YOUR_API_KEY",
"FirstQuadrant-Organization-ID": "org_YOUR_ORG_ID",
},
});