【发布时间】:2021-04-07 04:50:19
【问题描述】:
我一直在努力使用类验证器和 NestJS 验证以及尝试验证标头内容来验证请求。我的基本接口都在工作,但现在我正在尝试以相同的方式比较一些标题字段数据。
我有这个question about the custom decorator 来尝试处理标题,但该问题的解决方案将返回一个标题。我希望能够处理所有这些,类似于处理所有 body() 数据的方式。
我需要能够创建一个自定义装饰器来提取标题字段,并能够将它们传递给类验证器 DTO。
例如,我想验证三个头字段,例如:
User-Agent = 'Our Client Apps'
Content-Type = 'application/json'
traceabilityId = uuid
还有更多的领域,但如果我能做到这一点,那么我可以推断出其余的领域。我有一个简单的控制器示例:
@Controller(/rest/package)
export class PackageController {
constructor(
private PackageData_:PackageService
)
{ }
...
@Post('inquiry')
@HttpCode(HttpStatus.OK) // Not creating data, but need body, so return 200 OK
async StatusInquiry(
@RequestHeader() HeaderInfo:HeadersDTO, // This should be the Headers validation using the decorator from the question above.
我正在尝试验证请求的标头是否包含一些特定数据,并且我正在使用 NestJS。我找到了这个information。虽然这是我想要做的,而且看起来很合适,但 ClassType 引用不存在,我不确定要改用什么。
从例子中,装饰器指的是。
request-header.decorator.ts
export interface iError {
statusCode:number;
messages:string[];
error:string;
}
export const RequestHeader = createParamDecorator(
async (value: any, ctx: ExecutionContext) => {
// extract headers
const headers = ctx.switchToHttp().getRequest().headers;
// Convert headers to DTO object
const dto = plainToClass(value, headers, { excludeExtraneousValues: true });
// Validate
const errors: ValidationError[] = await validate(dto);
if (errors.length > 0) {
let ErrorInfo:IError = {
statusCode: HttpStatus.BAD_REQUEST,
error: 'Bad Request',
message: new Array<string>()
};
errors.map(obj => {
AllErrors = Object.values(obj.constraints);
AllErrors.forEach( (OneError) => {
OneError.forEach( (Key) => {
ErrorInfo.message.push(Key);
});
});
// Your example, but wanted to return closer to how the body looks, for common error parsing
//Get the errors and push to custom array
// let validationErrors = errors.map(obj => Object.values(obj.constraints));
throw new HttpException(`${ErrorInfo}`, HttpStatus.BAD_REQUEST);
}
// return header dto object
return dto;
},
我在将约束一般映射到字符串数组时遇到问题。
我的标头DTO.ts:
import { Expose } from 'class-transformer';
import { Equals, IsIn, IsString } from 'class-validator';
export class HeadersDTO {
@IsString()
@Equals('OurApp')
@Expose({ name: 'user-agent' })
public readonly 'user-agent':string;
@IsString()
@IsIn(['PRODUCTION', 'TEST'])
public readonly operationMode:string;
}
通过 Postman 发送请求的标头:
Content-Type:application/json
operationMode:PRODUCTION
Accept-Language:en
【问题讨论】:
-
我相信你点击了这个链接 - github.com/nestjs/nest/issues/4798。如果是,请交叉检查是否缺少任何东西
-
是的,除了找不到 ClassType 的问题仍然存在,它不会编译。
import { ClassType } from 'class-transformer/ClassTransformer'; -
错误是
Cannot find module 'class-transformer/ClassTransformer' or its corresponding type declarations.ts(2307) -
我已经在我发布的代码下面进行了测试,它对我有用
-
抱歉,没有看到您将 ClassType
更改为简单的 any。