Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 405
MIGUEL ANGEL ALONSO PEREZ Avatar asked Jul 04 '16 16:07

MIGUEL ANGEL ALONSO PEREZ


People also ask

What is CTX in Koa JS?

In Koa, I know that "ctx" stands for context, which encapsulates node's request and response objects.

What is Koa API?

Introduction. Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling.


1 Answers

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));
like image 116
zeronone Avatar answered Oct 24 '22 12:10

zeronone