koa2中间键原理

一、koa2

const http = require('http');
const compose = require('./compose');


class Koa {
  constructor() {
    this.ctx = {};
    this.middleWares = [];
  }

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

  handler(ctx, fnMiddleware) {
    fnMiddleware(ctx);
  }

  callback() {
    const fn = compose(this.middleWares);
    const handleRequest = () => {
      this.handler(this.ctx, fn);
    };
    return handleRequest;
  }

  listen(...args) {
    const server = http.createServer(this.callback());
    server.listen(...args);
  }
}

module.exports = Koa;

 

二、compose 中间键组合

function compose(middleWare) {
  return function fnMiddleWare(ctx) {
    function dispatch(i) {
      const fn = middleWare[i];
      if (!fn) return Promise.resolve();
      try {
        return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1)));
      } catch (error) {
        return Promise.reject(error);
      }
    }
    return dispatch(0);
  };
}

module.exports = compose;

 

posted @ 2019-05-14 18:56  shangyueyue  阅读(166)  评论(0编辑  收藏  举报