koakoa-router

Koa - Catch all routes that start with prefix


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 !


Solution

  • 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 *