📅  最后修改于: 2022-03-11 14:48:36.133000             🧑  作者: Mango
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,
});
};
}