实现一个简易的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'});

结果:

猜你喜欢

转载自www.cnblogs.com/shenshangzz/p/9687779.html