NestJS 使用类转换示例验证标题 [英] NestJS Validate Headers using class-transform example

查看:131
本文介绍了NestJS 使用类转换示例验证标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证请求的标头是否包含一些特定数据,并且我正在使用 NestJS.我找到了这个信息.虽然这是我想要做的,而且看起来很合适,但 ClassType 引用不存在,我不知道该用什么来代替.

I am trying to validate that the headers of the request contain some specific data, and I am using NestJS. I found this information. While this is what I want to do, and it looks proper, the ClassType reference does not exist, and I am not sure what to use instead.

从例子来看,装饰器指的是.

From the example, the decorator is referring to.

request-header.decorator.ts

request-header.decorator.ts

import { createParamDecorator, ExecutionContext } from '@nestjs/commom'
import { plainToClass } from 'class-transformer';
// The import below fails
import { ClassType } from 'class-transformer/ClassTransformer';
import { validateOrReject } from 'class-validator';

export const RequestHeader = createParamDecorator(
  async (value:  ClassType<unknown>, ctx: ExecutionContext) => {

    // extract headers
    const headers = ctx.switchToHttp().getRequest().headers;

    // Convert headers to DTO object
    const dto = plainToClass(value, headers, { excludeExtraneousValues: true });
    
    // Validate 
    await validateOrReject(dto);

    // return header dto object 
    return dto;
  },
);

推荐答案

与其像这样通过装饰器传递类型,我建议创建一个自定义装饰器并设置 validateCustomDecorators 选项ValidationPipetrue.装饰器看起来像

Rather than passing the type through a decorator like this, I'd suggest making a custom decorator and setting the validateCustomDecorators option for the ValidationPipe to true. The decorator would look something like

const Header = createParamDecorator((data: unknown, context: ExecutionContext) => {
  const req = context.switchToHttp().getRequest();
  if (data) {
    return req.headers[data];
  }
  return req.headers;
});

现在代替 @Header() 来自 @nestjs/common 你可以从这个文件中 @Header() 并得到ValidationPipe 在应用适当的类型元数据后运行

And now instead of @Header() from @nestjs/common you can you @Header() from this file and get the ValidationPipe to run after applying the appropriate type metadata

这篇关于NestJS 使用类转换示例验证标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆