0
votes

I'm trying to validate a GET request on Nest.js that has multiple queries using Joi. I understand how to use UsePipes and validate a single object on a single param. However I now have an endpoint that has the multiple queries, here is my controller:

  @Get(':cpId/search')
  @UsePipes(new JoiValidationPipe(queryDTOSchema))
  async getSomethingByFilters(
  @Param('cpId') cpId: string,
  @Query('startDate') startDate?: number,
  @Query('endDate') endDate?: number,
  @Query('el') el?: string,
  @Query('fields') fields?: string,
  @Query('keyword') keyword?: string,
  @Query('page') page?: number,
  @Query('limit') limit?: number,
  )...

And UsePipes is now validating the same schema against each of the queries, and I don't understand how to validate each single query separately.

Is there a way to validate each query separately? I couldn't find any references and the only solution I can think of would be to transform all those queries into a single object, which is undesirable in this case.

1

1 Answers

4
votes

You can pass a pipe as the second argument of a query-decorator:

@Query('startDate', new JoiValidationPipe(joi.number())) startDate?: number

But I personally would prefer validation as one query object, as it is easier to read and handle:

@Get(':corporatePartnerId/search')
async getEmployeesByFilters(
  @Param('corporatePartnerId', new JoiValidationPipe(joi.string())) corporatePartnerId: string,
  @Query(new JoiValidationPipe(QueryDtoSchema)) query: QueryDto,
)