/**
* Validates a JSON payload against a schema with retry logic.
* @param {object} payload The JSON payload to validate.
* @param {object} schema The JSON schema to validate against.
* @param {number} maxRetries The maximum number of retry attempts.
* @returns {Promise<boolean>} A promise that resolves to true if the payload is valid,
* or false if validation fails after all retries.
* @throws {Error} If payload or schema is not an object or maxRetries is not a number.
*/
async function validateJsonPayload(payload, schema, maxRetries = 3) {
if (typeof payload !== 'object' || payload === null) {
throw new Error("Payload must be an object.");
}
if (typeof schema !== 'object' || schema === null) {
throw new Error("Schema must be an object.");
}
if (typeof maxRetries !== 'number' || maxRetries <= 0 || !Number.isInteger(maxRetries)) {
throw new Error("maxRetries must be a positive integer.");
}
let retryCount = 0;
while (retryCount < maxRetries) {
try {
// Validate the payload against the schema
if (!isJsonValid(payload, schema)) {
retryCount++;
console.warn(`Validation failed (attempt ${retryCount}/${maxRetries}).`);
continue; // Retry
}
return true; // Validation successful
} catch (error) {
retryCount++;
console.warn(`Validation failed (attempt ${retryCount}/${maxRetries}): ${error.message}`);
}
}
console.error("Validation failed after multiple retries.");
return false; // Validation failed after all retries
}
/**
* Checks if a JSON payload is valid against a given schema.
* @param {object} payload The JSON payload.
* @param {object} schema The JSON schema.
* @returns {boolean} True if the payload is valid, false otherwise.
*/
function isJsonValid(payload, schema) {
try {
const Ajv = require('ajv'); // Import Ajv (install: npm install ajv)
const ajv = new Ajv();
const validate = ajv.compile(schema);
const valid = validate(payload);
if (!valid) {
throw new Error(`JSON validation failed: ${validate.errors.map(e => e.message).join(', ')}`);
}
return true;
} catch (error) {
throw new Error(`Error during JSON validation: ${error.message}`);
}
}
module.exports = validateJsonPayload;
Add your comment