/**
* Flags anomalies in API payloads with retry logic.
*
* @param {function} apiCall - Function to make the API call. Should return a promise resolving to the payload.
* @param {function} anomalyCheck - Function to check for anomalies in the payload. Should return true if anomalous, false otherwise.
* @param {object} options - Configuration options.
* @param {number} options.maxRetries - Maximum number of retry attempts.
* @param {number} options.retryDelay - Delay in milliseconds between retries.
* @returns {Promise<any>} - Promise resolving to the payload if successful, or rejecting with an error.
*/
async function flagPayloadAnomalies(apiCall, anomalyCheck, options = {}) {
const maxRetries = options.maxRetries || 3;
const retryDelay = options.retryDelay || 1000;
let retryCount = 0;
while (retryCount < maxRetries) {
try {
const payload = await apiCall(); // Make the API call
if (anomalyCheck(payload)) { // Check for anomalies
console.warn("Anomaly detected in payload:", payload);
return payload; // Return on anomaly detection
}
return payload; // No anomaly, return the payload
} catch (error) {
retryCount++;
console.error(`API call failed (attempt ${retryCount}/${maxRetries}):`, error);
if (retryCount < maxRetries) {
await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
} else {
throw error; // Re-throw if max retries reached
}
}
}
throw new Error("Max retries reached. API call failed."); //Re-throw if max retries reached
}
Add your comment