1. /**
  2. * Retries JSON payload validation operations with minimal configuration.
  3. *
  4. * @param {object} options Configuration options.
  5. * @param {Array<object>} options.payloads Array of JSON payloads to validate.
  6. * @param {number} options.maxRetries Maximum number of retries per payload. Defaults to 3.
  7. * @param {number} options.retryDelay Delay between retries in milliseconds. Defaults to 1000.
  8. * @param {function} options.validateFunction Function to validate the payload. Should return a boolean.
  9. * @returns {Promise<Array<object>>} A promise that resolves to an array of validation results.
  10. */
  11. async function retryJsonValidation(options) {
  12. const { payloads, maxRetries = 3, retryDelay = 1000, validateFunction } = options;
  13. if (!payloads || !Array.isArray(payloads) || payloads.length === 0) {
  14. return []; // Return empty array if no payloads are provided.
  15. }
  16. const results = [];
  17. for (const payload of payloads) {
  18. let attempts = 0;
  19. let isValid = false;
  20. while (attempts < maxRetries) {
  21. try {
  22. isValid = await validateFunction(payload); // Validate the payload
  23. if (isValid) {
  24. break; // Exit retry loop if valid
  25. }
  26. } catch (error) {
  27. attempts++;
  28. if (attempts < maxRetries) {
  29. await new Promise(resolve => setTimeout(resolve, retryDelay)); // Wait before retrying
  30. } else {
  31. console.error(`Validation failed after ${maxRetries} retries for payload:`, payload, error);
  32. }
  33. }
  34. }
  35. results.push({ payload, isValid });
  36. }
  37. return results;
  38. }

Add your comment