Search code examples
parametersnestjsquery-stringrouteparams

NestJS how to pass @Param and @Query in same request


I have this route set up:

  @Get('/name/like')
  findByLikeName(@Query() query: { supplierID: string; name: string }) {
    return this.supplierProductService.findByLikeName(query);
  }

Which utilises the query params in the underlying service:

  async findByLikeName({
    supplierID,
    name,
  }: {
    supplierID: string;
    name: string;
  }): Promise<SupplierProduct[]> {
    return await this.supplierProductRepository.findAll({
      where: {
        name: {
          [Op.like]: `%${name}%`,
        },
        supplierID: supplierID,
      },
    });
  }

However, let's say i want to move the supplierID into a /:supplierID route param, while maintaing the name (and potential other query params) in the query object, how would i go about implementing this?


Solution

  • You've pretty much already got it. All you should need to do is set up the @Get() route to know it's using a URL parameter and do the following:

      @Get('/name/like/:supplierID')
      findByLikeName(
        @Query() query: { name: string },
        @Param() param: { supplierID: string }
      ) {
        return this.supplierProductService.findByLikeName({...query, ...param});
      }