/**
* Checks configuration constraints with dry-run mode.
*
* @param {object} config The configuration object.
* @param {object} constraints An object defining the constraints for each config value.
* @param {boolean} dryRun Whether to only validate and not apply changes. Defaults to true.
* @returns {object} An object containing validation results. Includes 'errors' and 'warnings' arrays.
*/
function validateConfig(config, constraints, dryRun = true) {
const results = {
errors: [],
warnings: [],
};
for (const key in constraints) {
if (constraints.hasOwnProperty(key)) {
const constraint = constraints[key];
const value = config[key];
if (constraint.type === 'required' && value === undefined) {
results.errors.push({
key: key,
message: 'Value is required.',
});
continue;
}
if (constraint.type === 'string' && typeof value !== 'string') {
results.errors.push({
key: key,
message: 'Value must be a string.',
});
}
if (constraint.type === 'number' && typeof value !== 'number') {
results.errors.push({
key: key,
message: 'Value must be a number.',
});
}
if (constraint.min !== undefined && value < constraint.min) {
results.errors.push({
key: key,
message: `Value must be greater than or equal to ${constraint.min}.`,
});
}
if (constraint.max !== undefined && value > constraint.max) {
results.errors.push({
key: key,
message: `Value must be less than or equal to ${constraint.max}.`,
});
}
if (constraint.minLength !== undefined && value.length < constraint.minLength) {
results.errors.push({
key: key,
message: `Value must be at least ${constraint.minLength} characters long.`,
});
}
if (constraint.maxLength !== undefined && value.length > constraint.maxLength) {
results.errors.push({
key: key,
message: `Value must be at most ${constraint.maxLength} characters long.`,
});
}
if (constraint.pattern && typeof value !== 'string' && constraint.pattern) {
results.errors.push({
key: key,
message: 'Pattern validation only applies to strings.',
});
}
}
}
if (dryRun) {
return results; // Return results without applying changes
} else {
//In a real application, you would apply the changes here based on the validation results
//For this example, we just return the results.
return results;
}
}
Add your comment