NestJS:如何在@Query 对象中转换数组
Posted
技术标签:
【中文标题】NestJS:如何在@Query 对象中转换数组【英文标题】:NestJS: How to transform an array in a @Query object 【发布时间】:2020-04-04 23:11:13 【问题描述】:我是 NestJS 的新手,我正在尝试从查询参数中填充过滤器 DTO。
这是我所拥有的:
查询:
localhost: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[];
// ...
这样,类验证器就不会抱怨了,但是,在过滤器对象中,站实际上不是一个数组,而是一个字符串。
我想将其转换为验证管道中的数组。我怎样才能做到这一点?
【问题讨论】:
顺便说一句。它应该是:@Transform((value) => value.split(',')) 【参考方案1】:您可以传递ValidationPipe
的实例而不是类,这样做您可以传递诸如transform: true
之类的选项,这将使class-validator
和 class-transformer
运行,它应该传回转换后的值。
@Get()
public async getChecklists(@Query(new ValidationPipe( transform: true )) filter: ChecklistFilter): Promise<ChecklistDto[]>
// ...
【讨论】:
【参考方案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”
【讨论】:
嗨,关于如何在查询参数中为数字数组实现这一点的任何想法?想象一下我试图验证 [www.url.com/path?ids=1,2,3] ,其中 [ids] 应该是一个数字数组,仅此而已。尝试转换您的答案,但到目前为止没有成功。@IsArray() @IsInt( each: true ) @Transform(( value ) => value.trim().split(',').map(id=>Number(id))) @ApiProperty( type: [Number], format: 'form' ) ids?: number[];
/path?ids=1,2,3,4以上是关于NestJS:如何在@Query 对象中转换数组的主要内容,如果未能解决你的问题,请参考以下文章
如何从邮递员获取 CSV 文件并在 NestJs 上转换为数组