nodejs 實踐:express 最佳實踐(六) express 自省獲得所有的路由
某些情況下,你需要知道你的應用有多少路由,這在 express 中沒有方法可以。因此我這邊曲線了一下,做成了一個函數進行處理。遍歷所有的方法進行處理。
代碼
const _ = require('lodash');
const md5 = require('md5');const APP_USED = [];
const ROUTER = {};function printRouter() {_.each(APP_USED, function(used) {_.each(used.app._router.stack, function(stackElement) {if (stackElement.name === 'router') {stackElement.handle.stack.forEach((f) => {let path = f.route.path;let method = f.route.stack[0].method.toUpperCase();// console.log(method + ' -> ' + used.urlBase + path);_.updateWith(ROUTER, [used.urlBase], function(n) {if (n) {n.push({method,path: used.urlBase + path});} else {n = [];}return n;});});}});});let result = {};_.forEach(ROUTER, function(val) {val.forEach(v => {result[v.path] = md5(v.path);});});return result;
}module.exports = function(app) {let oldUse = app.use;app.use = function() {let urlBase = '';if (typeof arguments[0] === 'string') {urlBase = arguments[0];}_.forEach(arguments, function(arg) {if (arg.name === 'app') {APP_USED.push({urlBase: urlBase,app: arg});}});oldUse.apply(app, arguments);};return printRouter;
};
如何使用
在所有的路由中間件之前使用。