How to transform single item query string to array using class-validation

68 views Asked by At

I have a query string that works, such as

http://127.0.0.1:1000/api/cars/4?include=ford

but fails later because I am expecting an array.

How can I transform this using class-validation so that if there is only one entry in the include that it is an array.

export declare enum CarManuf {
  Ford = "ford",
  Chevy = "chevy",
  Honda = "honda"
}

export class CarsGetApiDto {
  //@Transform((value) => (Array.isArray(value) ? value : [value]), { toClassOnly: true })
  @IsOptional()
  @IsEnum(CarManuf, { each: true })
  include?: CarManuf[];
  
  ...
}

If I use the transform above I get an error stating

each value in include must be one of the following values: ford, chevy, honda

1

There are 1 answers

0
Lior Kupers On

Judging by this issue here, it seems like the order of validation is "reversed" (depends of course how you look at it).

In other words, try to reverse your order like this, or otherwise the transform takes place before the enum validation:

export declare enum CarManuf {
  Ford = "ford",
  Chevy = "chevy",
  Honda = "honda"
}

export class CarsGetApiDto {
  @IsOptional()
  @IsEnum(CarManuf, { each: true })
  @Transform((value) => (Array.isArray(value) ? value : [value]), { toClassOnly: true })
  include?: CarManuf[];
  
  ...
}