Search code examples
javascriptnode.jsexpressurl-routingkoa

Is there a Express-style nested router for Koa.js?


Is there exist a library that provides Express-style nesting routers? Something like this:

var koa = require('koa');
var app = koa();
var Router = require('???');

var restApiRouter = Router();
restApiRouter.get('/', function*() {
  // respond to /api/
});
restApiRouter.get('/messages', function*() {
  // respond to /api/messages
});

var appRouter = new Router();
appRouter.get('/', function*() {
  // respond to /
});
// redirects all /api/* requests to restApiRouter
appRouter.use('/api', restApiRouter);

app.use(appRouter);

If there isn't, what is the best practice to incapsulate common path routes in other files?


Solution

  • Previous answer didn't show exactly how to nest routers. Here is a real-world example, splitted in several controller files.

    First, we define some API routes into a controllers/api/foo.js file:

    var router = require('koa-router')();
    
    router.get('/', function* () {
        // Return a list of foos
    });
    
    router.get('/:id', function* () {
        // Return a specific foo
    });
    
    module.exports = router;
    

    Then, on your application router, you can embed it like the following, in a file controllers/index.js:

    var router = require('koa-router')();
    
    // Create a new route
    router.get('/', function* () {
        this.body = 'Home page';
    });
    
    // Nest previous API route
    router.get('/api/foo', require('./api/foo').routes());
    
    module.exports = router;
    

    Finally, just use the router into your application index.js:

    var koa = require('koa');
    var app = koa();
    app.use(require('./controllers').routes());
    app.listen(process.env.PORT || 3000);