1. /**
  2. * Wraps a function that processes a JSON payload with retry logic.
  3. *
  4. * @param {function} fn The function to execute with retry. Should accept a JSON payload as input.
  5. * @param {number} maxRetries The maximum number of retry attempts.
  6. * @param {number} delayMs The delay in milliseconds between retries.
  7. * @returns {function} A function that takes a JSON payload and executes the wrapped function with retry.
  8. */
  9. function retryWithDelay(fn, maxRetries, delayMs) {
  10. let retryCount = 0;
  11. /**
  12. * Executes the wrapped function with retry logic.
  13. * @param {object} payload The JSON payload to process.
  14. * @returns {Promise<any>} A promise that resolves with the result of the function or rejects if all retries fail.
  15. */
  16. return async function (payload) {
  17. return new Promise((resolve, reject) => {
  18. function attempt() {
  19. fn(payload) // Execute the original function
  20. .then(resolve)
  21. .catch(err => {
  22. retryCount++;
  23. if (retryCount >= maxRetries) {
  24. reject(err); // Reject the promise if max retries reached
  25. return;
  26. }
  27. setTimeout(() => {
  28. attempt(); // Retry after the specified delay
  29. }, delayMs);
  30. });
  31. }
  32. attempt(); // Start the first attempt
  33. });
  34. };
  35. }

Add your comment