Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS: How to transform an array in a @Query object

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?

like image 850
yuva.le Avatar asked Dec 11 '19 16:12

yuva.le


Video Answer


2 Answers

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-validatorand class-transformer run, which should pass back the transformed value.

@Get()
public async getChecklists(@Query(new ValidationPipe({ transform: true })) filter: ChecklistFilter): Promise<ChecklistDto[]> {
    // ...
}
like image 101
Jay McDoniel Avatar answered Sep 17 '22 15:09

Jay McDoniel


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[]> {
                // ...
            }
  • "class-transformer": "^0.4.0"
  • "class-validator": "^0.13.1"
like image 35
Juan Diego Garcia Avatar answered Sep 19 '22 15:09

Juan Diego Garcia