1. /**
  2. * Flags anomalies in API payloads with retry logic.
  3. *
  4. * @param {function} apiCall - Function to make the API call. Should return a promise resolving to the payload.
  5. * @param {function} anomalyCheck - Function to check for anomalies in the payload. Should return true if anomalous, false otherwise.
  6. * @param {object} options - Configuration options.
  7. * @param {number} options.maxRetries - Maximum number of retry attempts.
  8. * @param {number} options.retryDelay - Delay in milliseconds between retries.
  9. * @returns {Promise<any>} - Promise resolving to the payload if successful, or rejecting with an error.
  10. */
  11. async function flagPayloadAnomalies(apiCall, anomalyCheck, options = {}) {
  12. const maxRetries = options.maxRetries || 3;
  13. const retryDelay = options.retryDelay || 1000;
  14. let retryCount = 0;
  15. while (retryCount < maxRetries) {
  16. try {
  17. const payload = await apiCall(); // Make the API call
  18. if (anomalyCheck(payload)) { // Check for anomalies
  19. console.warn("Anomaly detected in payload:", payload);
  20. return payload; // Return on anomaly detection
  21. }
  22. return payload; // No anomaly, return the payload
  23. } catch (error) {
  24. retryCount++;
  25. console.error(`API call failed (attempt ${retryCount}/${maxRetries}):`, error);
  26. if (retryCount < maxRetries) {
  27. await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
  28. } else {
  29. throw error; // Re-throw if max retries reached
  30. }
  31. }
  32. }
  33. throw new Error("Max retries reached. API call failed."); //Re-throw if max retries reached
  34. }

Add your comment