I'm new to NestJS and I am trying to fill a filter DTO from query Parameters.
Here is what I have:
Query:
localhost:3000/api/checklists?stations=114630,114666,114667,114668
Controller
@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[];
// ...
}
With this, the class validator does not complain, however, in the filter object stations is not actually an array but still a single string.
I want to transform it into an array within the validation pipe. How can I achieve that?
You can pass an instance of the ValidationPipe
instead of the class, and in doing so you can pass in options such as transform: true
which will make class-validator
and class-transformer
run, which should pass back the transformed value.
@Get()
public async getChecklists(@Query(new ValidationPipe({ transform: true })) filter: ChecklistFilter): Promise<ChecklistDto[]> {
// ...
}