Answer the question
In order to leave comments, you need to log in
How to generate validation error output in NestJS?
I'm trying to do a validation following the example from the NestJS framework documentation . The problem is that the API response is given in case of an error in the form "{"statusCode": 400,"message": ["id must be a number string"],"error": "Bad Request"}".
I'd like to remake this to be the following:
// DTO
export class CreatePostDto {
@IsNumberString()
id: number;
}
...
// Controller
@Post()
async create(@Body() createPostDto: CreatePostDto) {
console.dir("CREATED")
}
Answer the question
In order to leave comments, you need to log in
Understood, in general. You just need to make your ValidationPipe:
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value, metadata: ArgumentMetadata) {
if (!value) {
throw new BadRequestException('No data submitted');
}
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
console.dir(object);
const errors = await validate(object);
if (errors.length > 0) {
throw new HttpException({message: 'Input data validation failed', errors: this.buildError(errors)}, HttpStatus.BAD_REQUEST);
}
return value;
}
private buildError(errors) {
const result = {};
errors.forEach(el => {
const prop = el.property;
Object.entries(el.constraints).forEach(constraint => {
result[prop] = constraint[0];
});
});
return result;
}
private toValidate(metatype): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find((type) => metatype === type);
}
}
@UsePipes(new ValidationPipe())
@Post()
async create(@Body() createPostDto: CreatePostDto) {
console.dir(createPostDto)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question