NestJS ValidationPipe 对于 @Query() 无法正常工作

Rus*_*Joe 3 javascript dto node.js nestjs

我正在尝试使用内置 NestJS ValidationPipe 将一些查询参数从字符串转换为整数,但它似乎无法正常工作,

这是我的控制器:

import {
..., ValidationPipe
} from '@nestjs/common';

...

@UseGuards(JwtAuthGuard)
@Get()
findAll(@Req() req, @Query(new ValidationPipe({
    transform: true,
    transformOptions: { enableImplicitConversion: true },
    forbidNonWhitelisted: true,
})) query: GetTestDto) {
    return this.testService.findAll(query, req.user.id);
}
Run Code Online (Sandbox Code Playgroud)

这是我的 DTO :

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

export class GetTestDto {
    @IsOptional()
    @IsString()
    public search: string;

    @IsOptional()
    @Transform(({value}) => {
        console.log(typeof value); // => string / I'm just testing here
        return value
    })
    @IsInt()
    public page: number;

    @IsOptional()
    @IsInt()
    public limit: number;
}
Run Code Online (Sandbox Code Playgroud)

主要.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import cookieParser from 'cookie-parser';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.setGlobalPrefix('api');
    app.use(cookieParser());
    app.useGlobalPipes(new ValidationPipe());
    await app.listen(3000);
}

bootstrap();
Run Code Online (Sandbox Code Playgroud)

当我尝试打电话时GET http://127.0.0.1:3000/api/test?page=1&limit=10我得到这个

validation error from the DTO I think:
{
    "statusCode": 400,
    "message": [
        "page must be an integer number",
        "limit must be an integer number"
    ],
    "error": "Bad Request"
} 
Run Code Online (Sandbox Code Playgroud)

我尝试删除 node_modules 和 dist 文件夹,但没有任何改变。我不想在 DTO 中使用 @Transform() 作为解决方案,我更希望管道通过enableImplicitConversion: true

我可以寻求帮助吗?

谢谢

小智 6

  1. main.ts传递文件中的 ValidationPipe 选项
app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
      whitelist: true,
    })
  );
Run Code Online (Sandbox Code Playgroud)
  1. 摆脱@Transformdto 类中的装饰器。

  2. 删除传递给@Query控制器​​中装饰器的ValidationPipe

@UseGuards(JwtAuthGuard)
@Get()
findAll(@Req() req, @Query() query: GetTestDto) {
    return this.testService.findAll(query, req.user.id);
}
Run Code Online (Sandbox Code Playgroud)