NestJS:如何在@Query 对象中转换数组

yuv*_*.le 7 class-validator nestjs class-transformer

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

这是我所拥有的:

询问:

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

控制器

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

DTO

export class ChecklistFilter {

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

Jay*_*iel 13

您可以传递 的实例而ValidationPipe不是类,并且在此过程中您可以传递诸如transform: truewhich will makeclass-validator class-transformerrun 之类的选项,这应该传回转换后的值。

@Get()
public async getChecklists(@Query(new ValidationPipe({ transform: true })) filter: ChecklistFilter): Promise<ChecklistDto[]> {
    // ...
}
Run Code Online (Sandbox Code Playgroud)


chr*_*arx 13

这可以在没有单独的 DTO 类的情况下使用以下方法来处理ParseArrayPipe

@Get()
findByIds(
  @Query('ids', new ParseArrayPipe({ items: Number, separator: ',' }))
  ids: number[],
) {
  console.log(ids);
  console.log(Array.isArray(ids)); //returns true
  return 'This action returns users by ids';
}
Run Code Online (Sandbox Code Playgroud)

参考:https://docs.nestjs.com/techniques/validation#parsing-and-validating-arrays


Jua*_*cia 12

export class ChecklistFilter {
    
            @IsOptional()
            @IsArray()
            @IsString({ each: true })
            @Type(() => String)
            @Transform(({ value }) => value.split(','))
            stations?: string[];
        
            // ...
        }
    
Run Code Online (Sandbox Code Playgroud)

--

     @Get()
     public async getChecklists(@Query() filter: ChecklistFilter): Promise<ChecklistDto[]> {
                // ...
            }
Run Code Online (Sandbox Code Playgroud)
  • “类变压器”:“^0.4.0”
  • “类验证器”:“^0.13.1”

  • `@IsArray() @IsInt({each: true }) @Transform(({ value }) =&gt; value.trim().split(',').map(id=&gt;Number(id))) @ApiProperty ({ type: [Number], format: 'form' }) ids?: number[];` **/path?ids=1,2,3,4** (6认同)

mav*_*riq 5

您可以稍微更改一下初始查询:

localhost:3000/api/checklists?stations[]=114630&stations[]=114666&stations[]=114667&stations[]=114668
Run Code Online (Sandbox Code Playgroud)

还有你的控制器:

@Get()
public async getChecklists(@Query('stations') filter: string[]): Promise<ChecklistDto[]> {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这样,默认机制将正常工作并将查询参数转换为字符串数组,并且不需要任何额外的依赖项或处理。

如果需要的话,您也可以用 DTO 包装它,但您明白了。