2

I'm trying to create a route that will act the same for different prefixes: koa-router with multiple prefixes for the same set of routes:

/player/:id
/players/:id     <- Same as above

/player/search
/players/search  <- Same as above

Both of those are exactly the same method, given twice for convenience of the users.

In Express, obtaining this is easy, as ? will make the s optional:

router.use('/players?', ...);

In Koa, this isn't valid.

I have tried creating a sub-router with the two options:

const router = new Router();
router.get('/:id', ...);

// And then:
const player = new Router();
player.use('/player', router.routes());
player.use('/players', router.routes());

But this will actually register:

players/player/:id

Replacing .use with .get will ignore router.routes() and register /player without :id.

Is there a way to achieve a router that accepts different routes without creating two separate routers?

Selfish
  • 6,023
  • 4
  • 44
  • 63
  • Koa-router resolves routes and its params using `path-to-regexp`: https://github.com/pillarjs/path-to-regexp maybe you can do some magic with that. I would not recommend it though. Why not point two separate routes to the same handler/middleware? You dont have to create a new router for that. – Spetastium Jun 27 '18 at 09:19
  • Imagine [this](https://github.com/javieraviles/node-typescript-koa-rest/blob/master/src/routes.ts) is your router config, cannot you simply use the same controller method for both paths? Another options, I have seen a [forwarding package](https://github.com/nswbmw/koa-forward-request) for koa, maybe you can have a look at the implementation and do it yourself? – Javier Aviles Jun 27 '18 at 12:02

0 Answers0