ValidationError.js 2.3 KB

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