Search code examples
javascriptnode.jsrouteskoa

Nodejs: Routing without type declaration


I am creating routers using koa. We have declared two routers as shown below.

app.get('/order/:id', async ctx => {
  const { id } = ctx.params;
  try {
    const data = await order.findOne({
      where: { order_id: id }
    });
    ctx.body = data;
  } catch (e) {
    ctx.body = e.message;
  }
});

app.get('/order/customer', async ctx => {
  const { id } = ctx.request.user;
  try {
    const data = await order.findOne({
      where: { customer_id: id }
    });
    ctx.body = data;
  } catch (e) {
    ctx.body = e.message;
  }
});

The first is a query that selects an order by order_id, and the second is a query that selects the order of the user with an id authenticated by the middleware.

curl http://localhost:3000/order/1

The order_id is 1 when I type in the above.

curl http://localhost:3000/order/customer

However, unlike my intention, when I enter the above, and check the query, the order_id is called customer. Is there any way I can make url simple to make /order/customer available?

If you have any questions I'm missing from the question or if you can help me, please comment or reply.


Solution

  • You're having the issue with order of routes definitions. You should have specific path route first and dynamic route later. Here, dynamic route I meant for /:id:

    '/order/customer' // first
    '/order/:id' // later