1

I'm trying to retrieve products from a specific company in my application using RESTful API.

The GET method that I'm trying to use is something like this:

http://localhost:3333/company/:company_id/products

So I tried this approach:

const routes = Router();

const company = `/company/:company_id`;
routes.use(`${company}/products`, productsRouter);

export default routes;

And then, inside the product router, I added this:

const productsRouter = Router();
const productsController = new ProductsController();

productsRouter.get('/', productsController.index);

export default productsRouter;

If I try to access the route through the browser or Insomnia it finds the route correctly, but I can't get the :company_id parameter from the first route. When I try to get it, but both request.params and request.query return nothing:

public async index(request: Request, response: Response): Promise<Response> {
    const { company_id } = request.params;
    const listProducts = container.resolve(ListProductsService);
    const products = await listProducts.execute(company_id);
    return response.json(products);
  }

Any thoughts on how to handle this situation?

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317

1 Answers1

0

Use mergeParams option of Router.

mergeParams

Preserve the req.params values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.

default value: false

const productsRouter = Router({mergeParams: true});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317