簡體   English   中英

通過 @IsInt() 驗證 application/x-www-form-urlencoded 請求類型

[英]Pass @IsInt() validation for application/x-www-form-urlencoded request type

當我瀏覽Pipes文檔時,我注意到我無法正確地對application/x-www-form-urlencoded請求進行@IsInt()驗證,因為我傳遞的所有值都作為字符串值接收。

我的請求數據如下所示在此處輸入圖像描述

我的 DTO 看起來像

import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
    @IsString()
    readonly name: string;

    @IsInt()
    readonly age: number;

    @IsString()
    readonly breed: string;
}

驗證管道包含下一個代碼

import { PipeTransform, Pipe, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Pipe()
export class ValidationPipe implements PipeTransform<any> {
    async transform(value, metadata: ArgumentMetadata) {
        const { metatype } = metadata;
        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);
    }
}

當我調試這個管道時,我注意到了這個狀態在此處輸入圖像描述 在哪里:

  • value - 請求正文值
  • 對象- 通過類轉換器值轉換
  • 錯誤- 錯誤對象

如您所見,錯誤告訴我們年齡必須是整數

如何通過@IsInt()驗證application/x-www-form-urlencoded請求?

庫版本:

  • @nestjs/common@4.6.4
  • 類變壓器@0.1.8
  • 類驗證器@0.8.1

PS:我還創建了一個存儲庫,您可以在其中運行應用程序來測試錯誤。 所需的分支how-to-pass-int-validation

UPD :從接受的答案進行更改后,我遇到了將錯誤的解析數據存儲到存儲中的問題。 記錄示例

是否有可能得到很好的解析createCatDto或者我需要做些什么來用正確的類型結構保存它?

application/x-www-form-urlencoded請求中的所有值始終是字符串。

因此,您可以執行以下操作:

import { Transform } from 'class-transformer';
import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
  @IsString()
  readonly name: string;

  @Transform(value => Number.isNan(+value) ? 0 : +value) // this field will be parsed to integer when `plainToClass gets called`
  @IsInt()
  readonly age: number;

  @IsString()
  readonly breed: string;
}

添加 @Type(() => Number) 為我解決了這個問題。

@IsNotEmpty({ message: '' })
@Type(() => Number)
@IsInt({ message: '' })
@ApiProperty()
project: number;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM