1

我有一个类,它有一个 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给自定义验证器类构造函数?

4

1 回答 1

0

如果将值声明为private,则它只能在类中访问。

您可以尝试使用readonly而不是通过公开使其可变。

于 2021-01-13T19:45:29.867 回答