Koa router bridge: easy way to make bridges for routes.
This plugin extends standart Koa router and allow to make simple and clean constructions to provide nested routes.
Usage:
; //-- import the module; // import standart koa-routerlet bridgedRouter = koaRouter; // patch the koa-router// make new routerlet router = ;
Now we have standart router with bridge extension. This is very helpful to define complete routes structure with using different middleware checks, nested structures and other. Let use it!
// get our routes structure (would be explained later); // set some usesrouter //-- let bridge it!router; /** attach complete router to your Koa app */ app;
Job complete! Now your router has complete path definitions for every nested elements, and for each of them will be executed necessary chains of conditions, data setting and other preparations.
Everything depends on routes functions. Let's explain them.
./app/routes.js
let router = /** for koa 1.* allowed generators and yield */ /** for example the base middleware must check for trailing slash into url */ init : async { let url = ctxreq_parsedUrl; let pathname = urlpathname; var checkExt = /.*[\.(xml|html|json)]$/; // requests with extensions must been skipped if pathname<0 && pathname!=='/' ctx; return; //-- add some through object e.g. ctx$$ = {}; //-- then go deeper await ; } // index router, just render index template index: async { await ctx; } // let init blog section blog: // init function must prepare some object for futher usage init: async { //-- store Blog for next usage ctx$$Blog = ; await ; } // then we can use this object for specific actions index: async { let data = await ctx$$Blog; await ctx; } // middleware before every request for /blog/:blogId checkId: async { var blogItem = await ctx$$Blog; if blogItem ctx$$blogItem = blogItem; await ; else ctx; } // viewItem would been executed if only `checkId` returns next(); viewItem: async { await ctx; } // the same for every specific output format itemJSON: async { ctx; } //... other code //-- same methods for shop init shop: init: async { ctx$$Shop = ; await ; } //... code for other methods // also we can require some extensions from other files other: // export our routermoduleexports = router;
Also we can import routes functions from specific files or write code right into router. This is not forbidden :)
;;/** ... */router;/** ... */router;// write the code into bridges router
P.S.:
koa-router-bridge may have some magic with roudex ;)