1. /**
  2. * Retries an API operation with fallback logic for validation checks.
  3. *
  4. * @param {function} apiCall - The function that performs the API call. Should return a Promise.
  5. * @param {number} maxRetries - The maximum number of retry attempts.
  6. * @param {number} delay - The delay (in milliseconds) between retries.
  7. * @param {function} fallbackValidation - A function to perform validation checks if the API call fails after retries.
  8. * @returns {Promise} A Promise that resolves with the API response or rejects with the fallback validation result.
  9. */
  10. async function retryApiCall(apiCall, maxRetries, delay, fallbackValidation) {
  11. let attempts = 0;
  12. while (attempts < maxRetries) {
  13. try {
  14. const response = await apiCall(); // Make the API call
  15. return response; // Success, return the response
  16. } catch (error) {
  17. attempts++;
  18. if (attempts === maxRetries) {
  19. // Last retry, use fallback validation
  20. return await fallbackValidation(error);
  21. }
  22. // Wait before retrying
  23. await new Promise(resolve => setTimeout(resolve, delay));
  24. }
  25. }
  26. }
  27. export default retryApiCall;

Add your comment