Validateur de classe personnalisé nid
useContainer(app.select(AppModule), { fallbackOnErrors: true });
@ValidatorConstraint({ name: 'UserExists', async: true })
@Injectable()
export class UserExistsRule implements ValidatorConstraintInterface {
constructor(private usersRepository: UsersRepository) {}
async validate(value: number) {
try {
await this.usersRepository.getOneOrFail(value);
} catch (e) {
return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
return `User doesn't exist`;
}
}
export function UserExists(validationOptions?: ValidationOptions) {
return function (object: any, propertyName: string) {
registerDecorator({
name: 'UserExists',
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: UserExistsRule,
});
};
}
DevPedrada