web-dev-qa-db-ja.com

NestJS:@Queryオブジェクトの配列を変換する方法

私は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[];

    // ...
}

これにより、クラスバリデーターは文句を言いませんが、フィルターオブジェクトステーションでは実際には配列ではなく単一の文字列です。

検証パイプ内で配列に変換したいのですが。どうすればそれを達成できますか?

3
yuva.le

クラスの代わりにValidationPipeのインスタンスを渡すことができます。その際、transform: trueなどのオプションを渡して、class-validatorandにすることができます。 class-transformer run。変換された値を返します。

@Get()
public async getChecklists(@Query(new ValidationPipe({ transform: true })) filter: ChecklistFilter): Promise<ChecklistDto[]> {
    // ...
}
1
Jay McDoniel