A koa router which supports chained route matching.
Trail is a router for koa with the option to explicitly execute multiple routes on a single request (similar to express routing).
For example, assume we have an authenticate middleware function which should run on every
/api/* route. Instead of:
// chain the authenticate on every routeappget'/api/users' authenticate apiControllergetUsers;appget'/api/profile/:userId' authenticate apiControllergetProfile;appget'/api/page/:pageId' authenticate apiControllergetPage;appput'/api/:contentId/like' authenticate apiControllerlikeContent;
We can simply apply the authentication handler once on a wildcard route:
appall'/api/*' authenticate;// the above route will be called before of any of the below routes matching /api/*// therefore, we don't need to explicitly chain it on each route.appget'/api/users' apiControllergetUsers;appget'/api/profile/:userId' apiControllergetProfile;appget'/api/page/:pageId' apiControllergetPage;appput'/api/:contentId/like' apiControllerlikeContent;
This reduces chaining on individual routes, and may improve security since there is less likelihood of a developer forgetting to add important security middleware on certain routes.
npm install koa-trail
var koa = require'koa';var trail = require'koa-trail';var app = koa;appusetrailapp;//now we can attach routesappget'/users'// ...;apppost'/users'// ...;
app is passed as a parameter to trail, it creates a method on the
app for every http method (get, post, put, delete, etc), plus app.all, app.register, and app.url. If you would prefer not to "pollute" the
app object with these methods, you may initialize a router object without passing the app parameter.
var koa = require'koa';var trail = require'koa-trail';var app = koa;var router = ;// pass the router.handler object, not the router object itselfappuserouterhandler;// now attach routes to the router object instead of approuterget'/users'// ...;routerpost'/users'// ...;
Routes can be named which makes them