14

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());
  • It's not very clear what your question is. – Andrei Zhytkevich Jul 04 '16 at 17:42
  • To the `app` they're all just middleware functions, whether they're router middleware (using koa-router) or some other middlewares (error handlers) is only known to you. Still, listing all middlewares `app` is using probably isn't documented. In express it can be done [like this](http://stackoverflow.com/questions/14934452/how-to-get-all-registered-routes-in-express) but express had a router of its own. So, this isn't an answer but I hope it helps in some way. I would inspect `app` to get all middlewares and see if any have a distinct feature to being one of that generated via koa-router – laggingreflex Jul 04 '16 at 18:15

1 Answers1

36

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));
zeronone
  • 2,912
  • 25
  • 28
  • I am using this solution, works nice, but I get some '(.*)' values inside the list, what do these mean? – Anto Jul 27 '19 at 21:20