我有一个类,它有一个 authToken 变量和一个带有自定义验证器的变量,需要使用 authToken 才能工作:
export default class ClassToValidate {
private authToken: string;
@MyCustomValidator()
fieldToValidate: SomeOtherClass;
// ... some other logic
}
@ValidatorConstraint({ async: true })
export class MyCustomValidatorConstraint implements ValidatorConstraintInterface {
private axiosInstance: AxiosInstance;
constructor() {
this.axiosInstance = axios.create({
baseURL: `www.someUrl.com`,
headers: {
'Authorization': //README: how can I set this to the authToken in ClassToValidate?
}
});
}
async validate(fieldToValidate: any, args: ValidationArguments) {
try {
const result = await this.axiosInstance.get(`${fieldToValidate}`, {});
return true
} catch (error) {
return false;
}
}
defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed
return "Something failed";
}
}
export function MyCustomValidator(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [],
validator: MyCustomValidatorConstraint
});
};
}
如何将 authToken 从实例传递ClassToValidate
给自定义验证器类构造函数?