Search code examples
typeormnestjs

How to handle TypeORM entity field unique validation error in NestJS?


I've set a custom unique validator decorator on my TypeORM entity field email. NestJS has dependency injection, but the service is not injected.

The error is:

TypeError: Cannot read property 'findByEmail' of undefined

Any help on implementing a custom email validator?

user.entity.ts:

@Column()
@Validate(CustomEmail, {
    message: "Title is too short or long!"
})
@IsEmail()
email: string;

My CustomEmail validator is

import {ValidatorConstraint, ValidatorConstraintInterface, 
ValidationArguments} from "class-validator";
import {UserService} from "./user.service";

@ValidatorConstraint({ name: "customText", async: true })
export class CustomEmail implements ValidatorConstraintInterface {

  constructor(private userService: UserService) {}
  async validate(text: string, args: ValidationArguments) {

    const user = await this.userService.findByEmail(text);
    return !user; 
  }

  defaultMessage(args: ValidationArguments) { 
    return "Text ($value) is too short or too long!";
  }
}

I know I could set unique in the Column options

@Column({
  unique: true
})

but this throws a mysql error and the ExceptionsHandler that crashes my app, so I can't handle it myself...

Thankx!


Solution

  • I have modified my code. I am checking the uniqueness of username/email in the user service (instead of a custom validator) and return an HttpExcetion in case the user is already inserted in the DB.