I have a custom validator constraint and annotation created for checking whether entity with given property already exists or not, here is the code
import { Inject, Injectable } from '@nestjs/common';
import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint } from 'class-validator';
import { ValidatorConstraintInterface } from 'class-validator/types/validation/ValidatorConstraintInterface';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';
@ValidatorConstraint({ async: true })
@Injectable()
export class EntityExistsConstraint implements ValidatorConstraintInterface {
constructor(@InjectConnection() private dbConnection: Connection) {
}
defaultMessage(validationArguments?: ValidationArguments): string {
return `${validationArguments.constraints[0].name} with ${validationArguments.property} already exists`;
}
validate(value: any, validationArguments?: ValidationArguments): Promise<boolean> | boolean {
const repoName = validationArguments.constraints[0];
const property = validationArguments.property;
const repository = this.dbConnection.getRepository(repoName);
return repository.findOne({ [property]: value }).then(result => {
return !result;
});
}
}
export function EntityExists(repoName, validationOptions?: ValidationOptions) {
return function(object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [repoName],
validator: EntityExistsConstraint,
});
};
}
Everything works fine, but I receive this response when the validation fails
{
"statusCode": 400,
"message": [
"User with email already exists"
],
"error": "Bad Request"
}
I want the error be Conflict Exception=> statusCode 409, how can I achieve this?
class-validator doesn't do anything with the http codes. It only validates and returns a list of errors or an empty array.
What you need to do is to check framework you use, I assume it's nestjs or routing-controllers.
In the case of routing-controllers you need to write own after middleware and disable default middleware (it converts validation errors to 400 bad requests). More info is here: https://github.com/typestack/routing-controllers#error-handlers
In the case of nestjs - the same steps. More info you can find here: https://docs.nestjs.com/exception-filters#catch-everything