1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.