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

时间:2016-09-04 14:34:01

标签: javascript node.js class middleware

我已经在谷歌和书籍上研究了几个小时的主题,我只能找到非常具体的实现。我很难在节点JS中编写一个简单的中间件类,只使用简单的vanilla javascript(没有像async,co,..这样的附加模块)。我的目标是了解它如何工作,而不是获得最优化的代码。

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

班级

"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 !!!'

2 个答案:

答案 0 :(得分:3)

对于那些寻找实际例子的人。

// 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'});

答案 1 :(得分:1)

接受的答案有一些问题,即未使用/未使用的变量。另外id就像发布一个替代答案,因为这就是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));
  }
}