1. /**
  2. * Instruments JSON payloads for validation checks.
  3. * Adds a 'validate' method to objects and checks against predefined schemas.
  4. *
  5. * @param {object} obj The object to instrument.
  6. * @param {object} schema The validation schema. Keys are field names, values are validation rules.
  7. * Example: { name: 'string', age: 'number >= 0' }
  8. * @returns {object} The instrumented object.
  9. */
  10. function instrumentJsonPayload(obj, schema) {
  11. if (typeof obj !== 'object' || obj === null) {
  12. return obj; // No validation needed for non-objects
  13. }
  14. const validate = function() {
  15. for (const key in schema) {
  16. if (schema.hasOwnProperty(key)) {
  17. const value = obj[key];
  18. const rule = schema[key];
  19. if (!validateValue(value, rule)) {
  20. throw new Error(`Validation failed for field '${key}': ${rule}`);
  21. }
  22. }
  23. }
  24. };
  25. obj.validate = validate; // Add validate method to the object
  26. return obj;
  27. }
  28. /**
  29. * Validates a single value against a validation rule.
  30. * @param {*} value The value to validate.
  31. * @param {string} rule The validation rule. Example: 'string', 'number >= 0', 'array'
  32. * @returns {boolean} True if the value is valid, false otherwise.
  33. */
  34. function validateValue(value, rule) {
  35. if (rule === 'string') {
  36. return typeof value === 'string';
  37. } else if (rule === 'number >= 0') {
  38. return typeof value === 'number' && value >= 0;
  39. } else if (rule === 'number <= 100') {
  40. return typeof value === 'number' && value <= 100;
  41. } else if (rule === 'array') {
  42. return Array.isArray(value);
  43. } else if (rule.startsWith('array')) {
  44. const parts = rule.split(' ');
  45. if (parts.length === 2 && parts[0] === 'array') {
  46. return Array.isArray(value) && value.length > 0;
  47. }
  48. } else if (rule.startsWith('object')) {
  49. const parts = rule.split(' ');
  50. if (parts.length === 2 && parts[0] === 'object') {
  51. return typeof value === 'object' && value !== null && !Array.isArray(value);
  52. }
  53. }
  54. else if (rule === 'required') {
  55. return value !== undefined && value !== null;
  56. }
  57. else {
  58. // Add more rules here as needed. Default to truthiness
  59. return value;
  60. }
  61. }

Add your comment