/**
* Instruments JSON payloads for validation checks.
* Adds a 'validate' method to objects and checks against predefined schemas.
*
* @param {object} obj The object to instrument.
* @param {object} schema The validation schema. Keys are field names, values are validation rules.
* Example: { name: 'string', age: 'number >= 0' }
* @returns {object} The instrumented object.
*/
function instrumentJsonPayload(obj, schema) {
if (typeof obj !== 'object' || obj === null) {
return obj; // No validation needed for non-objects
}
const validate = function() {
for (const key in schema) {
if (schema.hasOwnProperty(key)) {
const value = obj[key];
const rule = schema[key];
if (!validateValue(value, rule)) {
throw new Error(`Validation failed for field '${key}': ${rule}`);
}
}
}
};
obj.validate = validate; // Add validate method to the object
return obj;
}
/**
* Validates a single value against a validation rule.
* @param {*} value The value to validate.
* @param {string} rule The validation rule. Example: 'string', 'number >= 0', 'array'
* @returns {boolean} True if the value is valid, false otherwise.
*/
function validateValue(value, rule) {
if (rule === 'string') {
return typeof value === 'string';
} else if (rule === 'number >= 0') {
return typeof value === 'number' && value >= 0;
} else if (rule === 'number <= 100') {
return typeof value === 'number' && value <= 100;
} else if (rule === 'array') {
return Array.isArray(value);
} else if (rule.startsWith('array')) {
const parts = rule.split(' ');
if (parts.length === 2 && parts[0] === 'array') {
return Array.isArray(value) && value.length > 0;
}
} else if (rule.startsWith('object')) {
const parts = rule.split(' ');
if (parts.length === 2 && parts[0] === 'object') {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
}
else if (rule === 'required') {
return value !== undefined && value !== null;
}
else {
// Add more rules here as needed. Default to truthiness
return value;
}
}
Add your comment