如何在 Node.js 中编写中间件 class

How to write a middleware class in Node.js

我在 Google 和书籍上研究了这个主题几个小时,但我只能找到非常具体的实现。我正在努力在节点 JS 中编写一个简单的中间件 class,只有普通的 javascript(没有像 async,co,.. 这样的附加模块)。我的目标是了解如何获得最优化的代码。

我想要一些简单的东西,比如拥有一个字符串并通过使用中间件向它添加新字符串。

class

"use strict";
class Middleware {
    constructor() {
        this.middlewares = [];
    }
    use(fn) {
        this.middlewares.push(fn);
    }
    executeMiddleware(middlewares, msg, next) {
       // This is where I'm struggling
    }
    run(message) {
        this.executeMiddleware(this.middlewares, message, function(msg, next) {
            console.log('the initial message : '+ message);
        });
    }
}
module.exports = Middleware;

一种可能的用法

const Middleware = require('./Middleware');
const middleware = new Middleware();

middleware.use(function(msg, next) {
    msg += ' World';
    next();
});

middleware.use(function(msg, next) {
    msg += ' !!!';
    console.log('final message : ' + msg);
    next();
});
middleware.run('Hello');

因此,msg 变量最终将成为:'Hello World !!!'

对于那些正在寻找工作示例的人。

// MIDDLEWARE CLASS
"use strict";
let info = { msg: '' };

class Middleware {
    constructor() {
        this.middlewares = [];
    }

    use(fn) {
        this.middlewares.push(fn);
    }

    executeMiddleware(middlewares, data, next) {
        const composition = middlewares.reduceRight((next, fn) => v => {
            // collect next data
            info = data;
            fn(info, next)
        }, next);       
        composition(data);
    }

    run(data) {
        this.executeMiddleware(this.middlewares, data, (info, next) => {
            console.log(data);
        });
    }
}
module.exports = Middleware;

用法示例:

// index.js
const Middleware = require('./Middleware');
const middleware = new Middleware();

middleware.use(function(info, next) {
    info.msg += ' World';
    next();
});

middleware.use(function(info, next) {
    info.msg += ' !!!';
    next();
});

// Run the middleware with initial value
middleware.run({msg: 'Hello'});

接受的答案有几个问题,即 unused/uneeded 变量。我也喜欢 post 一个替代答案,因为这就是 stackexchange 的用途。

用法同上

class Middleware {
  constructor() {
    this.middlewares = [];
  }
  use(fn) {
     this.middlewares.push(fn);
  }
  executeMiddleware(data, done) {
    this.middlewares.reduceRight((done, next) => () => next(data, done), done)
(data);
  }
  run(data) {
    this.executeMiddleware(data, done => console.log(data));
  }
}