What i'm trying to do is propagate an error when some one tries to sign up with an email that's already in use. By default this returns a 500 error, but i need it to throw a meaningful error for this particular scenario. Note: The program returns a 500 error for every error
1 Answer
Yes, this is possible to validate email using class-validator
First of all you need to create custom class for this validator like this for example.
@ValidatorConstraint({ name: 'isEmailUserAlreadyExist', async: true })
@Injectable()
export class IsEmailUserAlreadyExistConstraint
implements ValidatorConstraintInterface
{
constructor(protected readonly usersService: UsersService) {}
async validate(text: string) {
return !(await this.usersService.userExists({
email: text,
}));
}
}
export function IsEmailUserAlreadyExist(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [],
validator: IsEmailUserAlreadyExistConstraint,
});
};
}
Then you need to import this class to the users module
providers: [UsersService, IsEmailUserAlreadyExistConstraint]
And after all, you can use this custom decorator in you DTO, where you can pass custom message as the error output
@IsEmailUserAlreadyExist({
message: 'Пользователь с таким email уже существует',
})
readonly email: string;
6 Comments
David Ekete
Thank you, this should help, but could you explain the syntax a little. it'll go a long way helping in creating mine when i want to change the functionality.
Father
Sure, first of all you need to create a class IsEmailUserAlreadyExistConstraint, decorate it with ValidatorConstraint and it must implement interface ValidatorConstraintInterface. By implementing this interface you expose method validate which takes some value from your DTO as string and must return true or false. That is the basic logic of class validator.
Father
Next, you need to decorate this class using Injectable decorator. It allows you to inject service or repository to the class constructor
Father
After, creating function IsEmailUserAlreadyExist just creates new decorator for code simplicity and possibility to use our class validation using one decorator
David Ekete
Thanks for all your help man, could you share a social media profile so that we can connect?
|