0

When I call /my/abc/create, I always get status 400 because of the first entrypoint. How can I call second endpoint? I prefer not to change the entrypoint order.

var Router = require('koa-router');

var router = Router();


router.get('/my/:path/:id', (ctx) =>{
    if (isNaN(Number(cox.params.id))) { // if not numeric
        ctx.status = 400;
        return;
    }
    console.log('route id')
})
router.get('/my/:path/create', (ctx) =>{ 
    console.log('route create')
})
Pytan
  • 1,138
  • 11
  • 28
  • Register the create route first. `I prefer not to change the entrypoint order`. Why? That's the only solution. – Adam Jenkins Oct 09 '21 at 20:24
  • oh is it an only solution? I thought there is a way... I don't wanna change the order because I might have more entry points like create, so I don't want to care about order every time I make new one – Pytan Oct 09 '21 at 20:26
  • My bad, definitely not the only solution, but the other solution requires checking in your first route if `ctx.params.id === 'create'` which is ugly. – Adam Jenkins Oct 09 '21 at 20:26
  • yeah I thought about the solution too, but if I make many entry points like create, the code will be messy. I wanna avoid it – Pytan Oct 09 '21 at 20:28
  • `so I don't want to care about order every time I make new one`. Well, if you don't want to care about the order, then you shouldn't make routes that can affect each other. For instance, the `create` route should probably be a POST and the `:id` route should probably be GET only. Typically, in RESTful design though, you don't have a verb like `create` in the URL, it's inferred by the fact that the request is a POST. – Adam Jenkins Oct 09 '21 at 20:28
  • true, I think I should do that – Pytan Oct 09 '21 at 20:30

1 Answers1

0

RESTfully speaking, you wouldn't have a create route at all:

router.get('/my/:path/:id', (ctx) => /* get entity */)
router.post('/my/:path', (ctx) => /* create entity */)
router.patch('/my/:path/:id', (ctx) => /* update entity */)
router.delete('/my/:path/:id', (ctx) => /* delete entity */)
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100