1. /**
  2. * Validates a JSON payload against a schema with retry logic.
  3. * @param {object} payload The JSON payload to validate.
  4. * @param {object} schema The JSON schema to validate against.
  5. * @param {number} maxRetries The maximum number of retry attempts.
  6. * @returns {Promise<boolean>} A promise that resolves to true if the payload is valid,
  7. * or false if validation fails after all retries.
  8. * @throws {Error} If payload or schema is not an object or maxRetries is not a number.
  9. */
  10. async function validateJsonPayload(payload, schema, maxRetries = 3) {
  11. if (typeof payload !== 'object' || payload === null) {
  12. throw new Error("Payload must be an object.");
  13. }
  14. if (typeof schema !== 'object' || schema === null) {
  15. throw new Error("Schema must be an object.");
  16. }
  17. if (typeof maxRetries !== 'number' || maxRetries <= 0 || !Number.isInteger(maxRetries)) {
  18. throw new Error("maxRetries must be a positive integer.");
  19. }
  20. let retryCount = 0;
  21. while (retryCount < maxRetries) {
  22. try {
  23. // Validate the payload against the schema
  24. if (!isJsonValid(payload, schema)) {
  25. retryCount++;
  26. console.warn(`Validation failed (attempt ${retryCount}/${maxRetries}).`);
  27. continue; // Retry
  28. }
  29. return true; // Validation successful
  30. } catch (error) {
  31. retryCount++;
  32. console.warn(`Validation failed (attempt ${retryCount}/${maxRetries}): ${error.message}`);
  33. }
  34. }
  35. console.error("Validation failed after multiple retries.");
  36. return false; // Validation failed after all retries
  37. }
  38. /**
  39. * Checks if a JSON payload is valid against a given schema.
  40. * @param {object} payload The JSON payload.
  41. * @param {object} schema The JSON schema.
  42. * @returns {boolean} True if the payload is valid, false otherwise.
  43. */
  44. function isJsonValid(payload, schema) {
  45. try {
  46. const Ajv = require('ajv'); // Import Ajv (install: npm install ajv)
  47. const ajv = new Ajv();
  48. const validate = ajv.compile(schema);
  49. const valid = validate(payload);
  50. if (!valid) {
  51. throw new Error(`JSON validation failed: ${validate.errors.map(e => e.message).join(', ')}`);
  52. }
  53. return true;
  54. } catch (error) {
  55. throw new Error(`Error during JSON validation: ${error.message}`);
  56. }
  57. }
  58. module.exports = validateJsonPayload;

Add your comment