ValidationErrorsFormatter.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { ValidationError } from 'class-validator';
  2. import { TDictionary } from '../types/TDictionary';
  3. export class ValidationErrorsFormatter {
  4. /**
  5. * @param {ValidationError[]} errors
  6. * @returns {string}
  7. */
  8. public static format (errors: ValidationError[]): string {
  9. return errors
  10. .reduce(
  11. (errorMessages: string[], error: ValidationError) => [
  12. ...errorMessages,
  13. ValidationErrorsFormatter.formatWithNestedConstraints(error)
  14. ],
  15. []
  16. )
  17. .join('\n');
  18. }
  19. /**
  20. * @param {ValidationError} error
  21. * @returns {string}
  22. */
  23. private static formatWithNestedConstraints (error: ValidationError): string {
  24. const constraints: TDictionary<string> | undefined = error.constraints;
  25. if (!constraints) {
  26. return `\`${error.property}\` error\n`;
  27. }
  28. const rootError: string = `\`${error.property}\` errors:\n`;
  29. const nestedErrors: string = Object
  30. .keys(constraints)
  31. .map((constraint: string) => ` - ${constraints[constraint]}\n`)
  32. .join();
  33. return `${rootError}${nestedErrors}`;
  34. }
  35. }