/**
* Validates API payload against predefined conditions with a timeout.
*
* @param {object} payload The API payload to validate.
* @param {object} conditions An object defining validation conditions. Keys are field names, values are validation functions.
* @param {number} timeoutMs Timeout in milliseconds.
* @returns {Promise<object|null>} A promise that resolves with the validated payload or null if validation fails. Rejects on timeout.
* @throws {Error} If conditions is not an object or timeoutMs is not a number.
*/
async function validatePayload(payload, conditions, timeoutMs) {
if (typeof conditions !== 'object' || conditions === null) {
throw new Error("Conditions must be an object.");
}
if (typeof timeoutMs !== 'number' || timeoutMs <= 0) {
throw new Error("Timeout must be a positive number.");
}
const startTime = Date.now();
for (const field in conditions) {
if (conditions.hasOwnProperty(field)) {
try {
const validationFunction = conditions[field];
const result = await validationFunction(payload[field]);
if (!result) {
console.warn(`Validation failed for field: ${field}`);
return null; // Validation failed
}
} catch (error) {
console.error(`Validation error for field ${field}:`, error);
return null; // Validation failed
}
}
}
return payload; // All validations passed
}
// Example validation functions (can be customized)
function isString(value) {
return typeof value === 'string' && value.length > 0;
}
function isNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
function isArray(value) {
return Array.isArray(value);
}
function isObject(value) {
return typeof value === 'object' && value !== null;
}
// Example usage:
// const payload = {
// name: "John Doe",
// age: 30,
// email: "john.doe@example.com",
// hobbies: ["reading", "hiking"]
// };
//
// const conditions = {
// name: isString,
// age: isNumber,
// email: isString,
// hobbies: isArray
// };
//
// const timeout = 5000; // 5 seconds
//
// validatePayload(payload, conditions, timeout)
// .then(validatedPayload => {
// if (validatedPayload) {
// console.log("Payload is valid:", validatedPayload);
// } else {
// console.log("Payload is invalid.");
// }
// })
// .catch(error => {
// console.error("Error:", error);
// });
Add your comment