ValidationErrorsFormatter.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { ValidationError } from 'class-validator';
  2. import { TObject } from '../types/TObject';
  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: TObject<string> = error.constraints;
  25. const rootError: string = `\`${error.property}\` errors:\n`;
  26. const nestedErrors: string = Object
  27. .keys(constraints)
  28. .map((constraint: string) => ` - ${constraints[constraint]}\n`)
  29. .join();
  30. return `${rootError}${nestedErrors}`;
  31. }
  32. }