nodejs 实践:express 最佳实践(六) express 自省获得所有的路由

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;
};

如何使用

在所有的路由中间件之前使用。

原文地址:https://www.cnblogs.com/htoooth/p/8321267.html