ValidationError.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ValidationError = void 0;
  4. /**
  5. * Validation error description.
  6. */
  7. class ValidationError {
  8. /**
  9. *
  10. * @param shouldDecorate decorate the message with ANSI formatter escape codes for better readability
  11. * @param hasParent true when the error is a child of an another one
  12. * @param parentPath path as string to the parent of this property
  13. * @param showConstraintMessages show constraint messages instead of constraint names
  14. */
  15. toString(shouldDecorate = false, hasParent = false, parentPath = ``, showConstraintMessages = false) {
  16. const boldStart = shouldDecorate ? `\x1b[1m` : ``;
  17. const boldEnd = shouldDecorate ? `\x1b[22m` : ``;
  18. const constraintsToString = () => { var _a; return (showConstraintMessages ? Object.values : Object.keys)((_a = this.constraints) !== null && _a !== void 0 ? _a : {}).join(`, `); };
  19. const propConstraintFailed = (propertyName) => ` - property ${boldStart}${parentPath}${propertyName}${boldEnd} has failed the following constraints: ${boldStart}${constraintsToString()}${boldEnd} \n`;
  20. if (!hasParent) {
  21. return (`An instance of ${boldStart}${this.target ? this.target.constructor.name : 'an object'}${boldEnd} has failed the validation:\n` +
  22. (this.constraints ? propConstraintFailed(this.property) : ``) +
  23. (this.children
  24. ? this.children
  25. .map(childError => childError.toString(shouldDecorate, true, this.property, showConstraintMessages))
  26. .join(``)
  27. : ``));
  28. }
  29. else {
  30. // we format numbers as array indexes for better readability.
  31. const formattedProperty = Number.isInteger(+this.property)
  32. ? `[${this.property}]`
  33. : `${parentPath ? `.` : ``}${this.property}`;
  34. if (this.constraints) {
  35. return propConstraintFailed(formattedProperty);
  36. }
  37. else {
  38. return this.children
  39. ? this.children
  40. .map(childError => childError.toString(shouldDecorate, true, `${parentPath}${formattedProperty}`, showConstraintMessages))
  41. .join(``)
  42. : ``;
  43. }
  44. }
  45. }
  46. }
  47. exports.ValidationError = ValidationError;
  48. //# sourceMappingURL=ValidationError.js.map