1. /**
  2. * Validates API payload against predefined conditions with a timeout.
  3. *
  4. * @param {object} payload The API payload to validate.
  5. * @param {object} conditions An object defining validation conditions. Keys are field names, values are validation functions.
  6. * @param {number} timeoutMs Timeout in milliseconds.
  7. * @returns {Promise<object|null>} A promise that resolves with the validated payload or null if validation fails. Rejects on timeout.
  8. * @throws {Error} If conditions is not an object or timeoutMs is not a number.
  9. */
  10. async function validatePayload(payload, conditions, timeoutMs) {
  11. if (typeof conditions !== 'object' || conditions === null) {
  12. throw new Error("Conditions must be an object.");
  13. }
  14. if (typeof timeoutMs !== 'number' || timeoutMs <= 0) {
  15. throw new Error("Timeout must be a positive number.");
  16. }
  17. const startTime = Date.now();
  18. for (const field in conditions) {
  19. if (conditions.hasOwnProperty(field)) {
  20. try {
  21. const validationFunction = conditions[field];
  22. const result = await validationFunction(payload[field]);
  23. if (!result) {
  24. console.warn(`Validation failed for field: ${field}`);
  25. return null; // Validation failed
  26. }
  27. } catch (error) {
  28. console.error(`Validation error for field ${field}:`, error);
  29. return null; // Validation failed
  30. }
  31. }
  32. }
  33. return payload; // All validations passed
  34. }
  35. // Example validation functions (can be customized)
  36. function isString(value) {
  37. return typeof value === 'string' && value.length > 0;
  38. }
  39. function isNumber(value) {
  40. return typeof value === 'number' && !isNaN(value);
  41. }
  42. function isArray(value) {
  43. return Array.isArray(value);
  44. }
  45. function isObject(value) {
  46. return typeof value === 'object' && value !== null;
  47. }
  48. // Example usage:
  49. // const payload = {
  50. // name: "John Doe",
  51. // age: 30,
  52. // email: "john.doe@example.com",
  53. // hobbies: ["reading", "hiking"]
  54. // };
  55. //
  56. // const conditions = {
  57. // name: isString,
  58. // age: isNumber,
  59. // email: isString,
  60. // hobbies: isArray
  61. // };
  62. //
  63. // const timeout = 5000; // 5 seconds
  64. //
  65. // validatePayload(payload, conditions, timeout)
  66. // .then(validatedPayload => {
  67. // if (validatedPayload) {
  68. // console.log("Payload is valid:", validatedPayload);
  69. // } else {
  70. // console.log("Payload is invalid.");
  71. // }
  72. // })
  73. // .catch(error => {
  74. // console.error("Error:", error);
  75. // });

Add your comment