Search code examples
nestjsclass-transformer

Nestjs transform JSON arra as string[]


I have the following get request:
/api?entitiesText=["america", "americans"]&phrasesText=["a month-long effort"]

I want to transform entitiesText and phrasesText to string[]:

export class ContentEnrichmentQuery {
    @IsArray()
    entitiesText?: string[];

    @IsArray()
    phrasesText?: string[];
}

This is the method:

@Get('/toppings')
async getViaPost(@Query(new ValidationPipe({ transform: true })) contentEnrichmentQuery: ContentEnrichmentQuery) {....}

Right now I get them as string and not string[]


Solution

  • URL and Query parameters will always come in as strings. That's how the underlying HTTP adapters and parsing packages work. If you want them to be non-string values you'll need to add a custom @Transform() decorator to these, like @Transform({value} => JSON.parse(value))