3

I was wondering how can we catch all API call of a specific route with KOA-Router. For example. I have an api designed like this :

/api/
/api/user/
/api/user/create
/api/user/login
/api/user/delete

How can I trigger the route /api/ for all calls that start with /api/ ? With expressJS you could do something like this to get all calls that start with a specific path:

app.get('/api/*', ()=>{}); 

but with KOA, the star '*' doesn't work, and I can't find something usefull inside the KOA documentation. Thank you for your help !

Tryall
  • 640
  • 12
  • 22

3 Answers3

3

I found the answer inside the path-to-regexp github readme. Koa use this for it's path matching.

https://github.com/pillarjs/path-to-regexp

They have an example showing how to do this :

const regexp = pathToRegexp("/:foo/(.*)");

So I just need to put (.*) instead of a simple *

Tryall
  • 640
  • 12
  • 22
1

Here is a quick exmaple. Make sure you call next() from the /api route to pass the request down the middleware stack.

const Koa = require('koa')
const Router = require('@koa/router')

const app = new Koa()
const router = new Router()

router.get('/api(.*)', (ctx, next) => {
  ctx.body = 'You hit the /api route'
  next()
})

router.get('/api/user', (ctx) => {
  ctx.body += '\nYou hit the /api/user route'
})

router.get('/api/user/create', (ctx) => {
  ctx.body += '\nYou hit the /api/user/create route'
})

app.use(router.routes())

app.listen(3000)
Dominic Egginton
  • 346
  • 2
  • 10
1

Good to know this also works:

router.get("/static/:path(.*)", async function(ctx, next) {
  console.log(ctx.params);
  next();
});

Result:

{ path: 'test/1/2/3' }
Rinnert
  • 11
  • 1