1. /**
  2. * Checks configuration constraints with dry-run mode.
  3. *
  4. * @param {object} config The configuration object.
  5. * @param {object} constraints An object defining the constraints for each config value.
  6. * @param {boolean} dryRun Whether to only validate and not apply changes. Defaults to true.
  7. * @returns {object} An object containing validation results. Includes 'errors' and 'warnings' arrays.
  8. */
  9. function validateConfig(config, constraints, dryRun = true) {
  10. const results = {
  11. errors: [],
  12. warnings: [],
  13. };
  14. for (const key in constraints) {
  15. if (constraints.hasOwnProperty(key)) {
  16. const constraint = constraints[key];
  17. const value = config[key];
  18. if (constraint.type === 'required' && value === undefined) {
  19. results.errors.push({
  20. key: key,
  21. message: 'Value is required.',
  22. });
  23. continue;
  24. }
  25. if (constraint.type === 'string' && typeof value !== 'string') {
  26. results.errors.push({
  27. key: key,
  28. message: 'Value must be a string.',
  29. });
  30. }
  31. if (constraint.type === 'number' && typeof value !== 'number') {
  32. results.errors.push({
  33. key: key,
  34. message: 'Value must be a number.',
  35. });
  36. }
  37. if (constraint.min !== undefined && value < constraint.min) {
  38. results.errors.push({
  39. key: key,
  40. message: `Value must be greater than or equal to ${constraint.min}.`,
  41. });
  42. }
  43. if (constraint.max !== undefined && value > constraint.max) {
  44. results.errors.push({
  45. key: key,
  46. message: `Value must be less than or equal to ${constraint.max}.`,
  47. });
  48. }
  49. if (constraint.minLength !== undefined && value.length < constraint.minLength) {
  50. results.errors.push({
  51. key: key,
  52. message: `Value must be at least ${constraint.minLength} characters long.`,
  53. });
  54. }
  55. if (constraint.maxLength !== undefined && value.length > constraint.maxLength) {
  56. results.errors.push({
  57. key: key,
  58. message: `Value must be at most ${constraint.maxLength} characters long.`,
  59. });
  60. }
  61. if (constraint.pattern && typeof value !== 'string' && constraint.pattern) {
  62. results.errors.push({
  63. key: key,
  64. message: 'Pattern validation only applies to strings.',
  65. });
  66. }
  67. }
  68. }
  69. if (dryRun) {
  70. return results; // Return results without applying changes
  71. } else {
  72. //In a real application, you would apply the changes here based on the validation results
  73. //For this example, we just return the results.
  74. return results;
  75. }
  76. }

Add your comment