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

    如何使用

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

  • 相关阅读:
    python之路1:介绍和入门
    SpringMVC学习指南【笔记3】基于注解的控制器
    SpringMVC学习指南【笔记2】简介、校验器、配置
    SpringMVC学习指南【笔记1】创建bean实例的方法和依赖注入
    2018-12-18笔记
    elastic-job简介
    Java中由于数据太大自动转换成科学计数法解决方式
    Redis主从复制
    Redis数据类型
    Redis的基本命令
  • 原文地址:https://www.cnblogs.com/htoooth/p/8321267.html
Copyright © 2020-2023  润新知