Search code examples
node.jskoakoa-router

How can i get a list of Koa server url routes


I'm developing a mock server using koajs, and i would like to publish a service which lists developed APIs.

I use koa-router for mouting services.

And i would like somethink like:

var business_router = require('./controllers/router');
app.use(business_router.routes());   
app.use(business_router.allowedMethods());

console.log(app.listRoutes());

Solution

  • Although I guess it is not part of the official koa-router API, you can do as following:

    var app = require('koa')();
    var router = require('koa-router')();
    
    router.get('/bar', function*() { this.body = 'Hi'; }});
    router.get('/bar/foo', function*() { this.body = 'Hi'; }});
    router.get('/foo', function*() { this.body = 'Hi'; }});
    router.get('/bar/baz', function*() { this.body = 'Hi'; }});
    
    app
      .use(router.routes())
      .use(router.allowedMethods());
    
    console.log(router.stack.map(i => i.path));
    // ['/bar', '/bar/foo', '/foo', '/bar/baz']
    

    In your case, assuming business_router is an instance of koa-router:

    console.log(business_router.stack.map(i => i.path));