查询参数总是以字符串形式出现,如果您使用 URL 参数,它们也是如此。修改它就@Type(() => Number)
足够了,但你需要确保你已经transform: true
在你的ValidationPipe
.
import { Type } from 'class-transformer';
import { IsArray, IsNumber } from 'class-validator';
export class NumbersQuery {
@Type(() => Number)
@IsArray()
@IsNumber({}, {each: true})
numbers: number[];
}
import { Controller, Get, Query, UsePipes, ValidationPipe } from '@nestjs/common';
import { AppService } from './app.service';
import { NumbersQuery } from './numbers';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(@Query() query: Record<string, unknown>): string {
return this.appService.getHello(query);
}
@UsePipes(new ValidationPipe({ transform: true }))
@Get('numbers')
getNumbers(@Query() numbers: NumbersQuery) {
console.log(numbers);
return numbers.numbers;
}
}
▶ curl http://localhost:3000/numbers/\?numbers\[\]\=1\&numbers\[\]\=2
[1,2]%
[Nest] 76497 - 10/23/2020, 10:40:47 AM [NestFactory] Starting Nest application...
[Nest] 76497 - 10/23/2020, 10:40:47 AM [InstanceLoader] AppModule dependencies initialized +11ms
[Nest] 76497 - 10/23/2020, 10:40:47 AM [RoutesResolver] AppController {}: +5ms
[Nest] 76497 - 10/23/2020, 10:40:47 AM [RouterExplorer] Mapped {, GET} route +2ms
[Nest] 76497 - 10/23/2020, 10:40:47 AM [RouterExplorer] Mapped {/numbers, GET} route +1ms
[Nest] 76497 - 10/23/2020, 10:40:47 AM [NestApplication] Nest application successfully started +1ms
NumbersQuery { numbers: [ 1, 2 ] }