【问题标题】:How to pass auth token from class to custom validator?如何将身份验证令牌从类传递到自定义验证器?
【发布时间】:2020-05-21 17:49:18
【问题描述】:

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

【问题讨论】:

    标签: javascript typescript api class-validator


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 2015-09-13
      • 2021-08-17
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多