美文网首页
express中间件的实现方式

express中间件的实现方式

作者: 一个废人 | 来源:发表于2018-06-14 11:32 被阅读15次
class Task{
  constructor(){
    this.plugins = {
      '*': []
    };
    this.pluginId = 0;
  }
  use(router, functor){
    if(typeof router === 'function'){
      [router, functor] = ['*', router];
    }
    this.plugins[router] = this.plugins[router] || [];
    this.plugins[router].push({
      functor,
      id: ++this.pluginId
    });
  }
  dispatch(router, ...args){
    let plugins = this.plugins['*'];
    if(router !== '*'){
      plugins = plugins.concat(this.plugins[router] || []);
    }
    plugins.sort((a, b) => a.id - b.id);
    
    let entrace = plugins.map(plugin => plugin.functor.bind(this, ...args)) // 柯里化同一传参数。
                         .reduceRight((a, b) => b.bind(this, a));
                          // 阻塞函数运行,除非在回调函数里面调用下一个函数。
    
    entrace();
  }
}

let task = new Task();

task.use(function(req, res, next){
  console.log(req, res);
  next();
});

task.use('/', function(req, res, next){
  req.a++;
  res.x++;
});

task.use('/', function(req, res,next){
  console.log(req, res);
  next()
});

task.use('/', function(req, res){
});

task.dispatch('/', {a: 1}, {x: 2});

相关文章

网友评论

      本文标题:express中间件的实现方式

      本文链接:https://www.haomeiwen.com/subject/wfaeeftx.html