zoukankan      html  css  js  c++  java
  • 实现一个简易的express中间件

    代码:

    // 通过闭包实现单例
    const Middlewave = (function(){
        let instance;
        class Middlewave{
            constructor() {
                this.stack = [];    // 中间件调用栈
                return instance || (instance = this);    //    返回单例
            }
            // 注册中间件
            use(...funcs) {
                // 将中间件push到stack调用栈中
                funcs.forEach(func => this.stack.push(func));
            }
            // 调用下一个中间件
            next() {
                if (this.stackCopy[0]) {
                    // 取出当前中间件
                    const curWave = this.stackCopy.shift();
                    // 执行当前中间件
                    // next绑定this,防止this指向被修改
                    curWave(this.req, this.res, this.next.bind(this));
                }
            }
            init(req, res) {
                this.req = req;
                this.res = res;
                // 复制一份中间件调用栈调用栈
                this.stackCopy = this.stack.map(item => item);
                // 执行下一步
                this.next();
            }
        }
        return Middlewave;
    })();

    测试:

    const app = new Middlewave();
    
    function middlewave_a(req, res, next) {
        req.a = true;
        res.a = true;
        console.log('a', req, res);
        next();
    }
    
    function middlewave_b(req, res, next) {
        req.b = true;
        res.b = true;
        console.log('b', req, res);
        next();
    }
    
    function middlewave_c(req, res, next) {
        req.c = true;
        res.c = true;
        console.log('c', req, res);
    }
    
    function middlewave_d(req, res, next) {
        req.d = true;
        res.d = true;
        console.log('d', req, res);
        next();
    }
    
    app.use(middlewave_a);
    app.use(middlewave_b);
    app.use(middlewave_c);
    app.use(middlewave_d);
    
    app.init({name: 'a'}, { name: 'a'});
    app.init({name: 'b'}, { name: 'b'});
    app.init({name: 'c'}, { name: 'c'});

    结果:

  • 相关阅读:
    TCP协议与UDP协议的区别
    打印阵列
    Java的动态代理机制详解(转)
    Java内存模型(转载)
    Hibernate工作原理及为什么要用?(转http://www.cnblogs.com/javaNewegg/archive/2011/08/28/2156521.html)
    SpringMVC工作原理
    FPGrowth算法原理
    十大排序之快速排序
    python logging
    把字符串转换成整数
  • 原文地址:https://www.cnblogs.com/shenshangzz/p/9687779.html
Copyright © 2011-2022 走看看