validation.pipe.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {
  2. PipeTransform,
  3. Injectable,
  4. ArgumentMetadata,
  5. BadRequestException,
  6. } from '@nestjs/common';
  7. import { validate } from 'class-validator';
  8. import { plainToClass } from 'class-transformer';
  9. @Injectable()
  10. export class ValidationPipe implements PipeTransform<any> {
  11. async transform(value, { metatype }: ArgumentMetadata) {
  12. if (!metatype || !this.toValidate(metatype)) {
  13. return value;
  14. }
  15. const object = plainToClass(metatype, value);
  16. // when value is null, metatype exist, object will be null
  17. if (object === null) {
  18. throw new BadRequestException('params should not be empty');
  19. }
  20. // interface ValidatorOptions {
  21. // skipMissingProperties?: boolean;
  22. // whitelist?: boolean;
  23. // forbidNonWhitelisted?: boolean;
  24. // groups?: string[];
  25. // dismissDefaultMessages?: boolean;
  26. // validationError?: {
  27. // target?: boolean;
  28. // value?: boolean;
  29. // };
  30. // forbidUnknownValues?: boolean;
  31. // }
  32. const errors = await validate(object, {
  33. skipMissingProperties: false,
  34. whitelist: true,
  35. forbidNonWhitelisted: true,
  36. });
  37. errors.forEach((error) => {
  38. let constraints = error.constraints;
  39. let currentError = error;
  40. while (!constraints && currentError) {
  41. constraints = currentError.constraints;
  42. currentError = currentError.children[0];
  43. }
  44. for (const i in constraints) {
  45. throw new BadRequestException(constraints[i]);
  46. }
  47. });
  48. return value;
  49. }
  50. private toValidate(metatype): boolean {
  51. const types = [String, Boolean, Number, Array, Object];
  52. return !types.find((type) => metatype === type);
  53. }
  54. }