NESTJS验证管道和带有服务层的CustomValidatorDecorator

时间:2018-10-24 11:01:22

标签: typescript nestjs

您好,我最近是NESTJS的新手,我需要帮助来解决此问题。问题在于,我需要在验证管道上访问调用令牌的请求的令牌(具有相同的令牌)并使用HttpModule来检查发送的ID是否有效。

验证管道(来自nestjs文档的示例):

@Override
public void configure(WebSecurity webSecurity) {
    webSecurity.ignoring().antMatchers("/public/pic/**");
}

自定义验证程序:

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException('Validation failed');
    }
    return value;
  }

  private toValidate(metatype): boolean {
    const types = [String, Boolean, Number, Array, Object];
    return !types.find((type) => metatype === type);
  }
}

有什么建议,我在DTO上放置了装饰器进行验证,然后他自动调用api以检查language_id是否存在。

import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function IsLanguageValid(property: string, validationOptions?: ValidationOptions) {
  return function(object: Object, propertyName: string) {
    registerDecorator({
      name: 'isLanguageValid',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [relatedPropertyName] = args.constraints;
          const relatedValue = (args.object as any)[relatedPropertyName];

          // WHERE HOW CAN I ACCESS TO A SERVICE AND TOKEN OF THE REQUEST
          this.httpModule.get('url to other api', { headers: { authrorization : TOKEN }})
        },
      },
    });
  };
}

0 个答案:

没有答案