9

我是 NestJS 的新手,我正在尝试从查询参数中填充过滤器 DTO。

这是我所拥有的:

询问:

本地主机:3000/api/checklists?stations=114630,114666,114667,114668

控制器

@Get()
public async getChecklists(@Query(ValidationPipe) filter: ChecklistFilter): Promise<ChecklistDto[]> {
    // ...
}

DTO

export class ChecklistFilter {

    @IsOptional()
    @IsArray()
    @IsString({ each: true })
    @Type(() => String)
    @Transform((value: string) => value.split(','))
    stations?: string[];

    // ...
}

有了这个,类验证器不会抱怨,但是,在过滤器对象中,站实际上不是一个数组,而是一个字符串。

我想将其转换为验证管道中的数组。我怎样才能做到这一点?

4

2 回答 2

8

你可以传递一个实例ValidationPipe而不是类,这样做你可以传递诸如transform: truewhich will make class-validatorand class-transformer run之类的选项,它应该传回转换后的值。

@Get()
public async getChecklists(@Query(new ValidationPipe({ transform: true })) filter: ChecklistFilter): Promise<ChecklistDto[]> {
    // ...
}
于 2019-12-11T16:28:02.340 回答
2
export class ChecklistFilter {
    
            @IsOptional()
            @IsArray()
            @IsString({ each: true })
            @Type(() => String)
            @Transform(({ value }) => value.split(','))
            stations?: string[];
        
            // ...
        }
    

--

     @Get()
     public async getChecklists(@Query() filter: ChecklistFilter): Promise<ChecklistDto[]> {
                // ...
            }
  • “类转换器”:“^0.4.0”
  • “类验证器”:“^0.13.1”
于 2021-10-18T02:19:01.093 回答