I can't validate email is unique using ajv
If i understand your problem, you would like to have an error message when saving a model with an already used email in your storage.
To do that, you have to acces to your storage to verify email property in all your data.
Ajv doesn't have access to your storage, it just allows you to validate string pattern on object fields.
But, if you use an orm like typeorm, you can add unique contraint on email property.
// UserModel.ts
@Entity()
@Unique(['email']) // orm (database constraint)
export class User {
@Email() // ajv
@Required() // ajv
@Column() // orm
email: string;
}
And,
Option 1: check before saving if entity with this email exist
// UserController.ts
@Controller()
export class UserController {
@Post("/")
private async create(@BodyParams() user: CreateUserModel): Promise<User> {
const userFind = await this.userService.find({ email: user.email});
if(userFind) {
return // something
}
return this.userService.save(<User>user);
}
}
Option 2: handle duplicate entry error
// GlobalErrorHandlerMiddleware.ts
// ...
if (error instanceof QueryFailedError) {
if(error.code === 'ER_DUP_ENTRY') {
// do something
}
}
// ...
This is TypeORM's thing. In addition to putting the external validation of @Email() as @amourlanne says, you can do @Column({ unique: true })
@Description('User email')
@Column({ unique: true })
@Email()
email: string
Error capture:

Most helpful comment
If i understand your problem, you would like to have an error message when saving a model with an already used email in your storage.
To do that, you have to acces to your storage to verify email property in all your data.
Ajv doesn't have access to your storage, it just allows you to validate string pattern on object fields.
But, if you use an orm like typeorm, you can add unique contraint on email property.
And,
Option 1: check before saving if entity with this email exist
Option 2: handle duplicate entry error