Convert string array to array in validation pipe nestjs

Viewed 85

I get the following item back from my api controller call using this query http://you.host/api/v1/all?lookup=["s1","s2"] :

{ lookup: '["s1", "s2"]' }

Class validator and transformer

export class Filter {
  @Type(() => String)
  @IsArray()
  @IsString({ each: true })
  lookup?: string[];
}

Controller

@UsePipes(new ValidationPipe({ transform: true }))
  @Get('all')
  async getAll(@Query() data: Filter): Promise<string[]> {
    console.log(data)
    return data
  }

I want

{ lookup: ["s1", "s2"] }

In my JavaScript I tried services = JSON.parse(data) - didn't do anything

1 Answers

The problem is with the returned data. lookup is actually returned as a string.

{ lookup: '["s1", "s2"]' }

Either fix the api to send an array of strings or try this

const data = { lookup: '["s1", "s2"]' }
const parsedData = {
    lookup: JSON.parse(data.lookup)
}
Related