|
| 1 | +import { ArgumentMetadata, HttpStatus, Injectable, Logger, ValidationError, ValidationPipe, ValidationPipeOptions } from '@nestjs/common' |
| 2 | + |
| 3 | +interface ValidationRecursive { |
| 4 | + [key: string]: string |
| 5 | +} |
| 6 | + |
| 7 | +@Injectable() |
| 8 | +export class DtoValidationPipe extends ValidationPipe { |
| 9 | + public constructor(options?: ValidationPipeOptions) { |
| 10 | + super({ |
| 11 | + transform: true, |
| 12 | + transformOptions: { |
| 13 | + enableImplicitConversion: true, |
| 14 | + }, |
| 15 | + exceptionFactory: (errors: ValidationError[]) => this.exceptionHandler(errors), |
| 16 | + ...options, |
| 17 | + }) |
| 18 | + } |
| 19 | + |
| 20 | + public async transform(value: any, metadata: ArgumentMetadata): Promise<any> { |
| 21 | + return (await super.transform(value, metadata)) || value; |
| 22 | + } |
| 23 | + |
| 24 | + public exceptionHandler(errors: ValidationError[]) { |
| 25 | + let validations: ValidationRecursive = {} |
| 26 | + for (const error of errors) { |
| 27 | + validations = { ...validations, ...this.validationRecursive(error) } |
| 28 | + } |
| 29 | + |
| 30 | + const message = `Erreur de validation : ${Object.keys(validations).join(', ')}`.trim() |
| 31 | + Logger.debug(`${message} (${JSON.stringify(validations)})`, DtoValidationPipe.name) |
| 32 | + |
| 33 | + return { |
| 34 | + statusCode: HttpStatus.BAD_REQUEST, |
| 35 | + message, |
| 36 | + validations, |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + protected validationRecursive(error: ValidationError, prefix = ''): ValidationRecursive { |
| 41 | + let validations = {} |
| 42 | + if (error.constraints) { |
| 43 | + validations[`${prefix + error.property}`] = Object.values(error.constraints)[0] |
| 44 | + } |
| 45 | + if (error.children.length > 0) { |
| 46 | + for (const errorChild of error.children) { |
| 47 | + if (errorChild.constraints) { |
| 48 | + validations[`${prefix + error.property}.${errorChild.property}`] = Object.values(errorChild.constraints)[0] |
| 49 | + } |
| 50 | + if (errorChild.children.length > 0) { |
| 51 | + validations = { ...validations, ...this.validationRecursive(errorChild, `${prefix + error.property}.${errorChild.property}.`) } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + return validations |
| 56 | + } |
| 57 | +} |
0 commit comments