express 和 koa

2020-03-31  本文已影响0人  看到这朵小fa了么

express

中间件

express和koa的区别


中间件的实现

// 简单实现express

const http = require("http");
const slice = Array.prototype.slice;

class LikeExpress {
  constructor() {
    this.routes = {
      all: [],
      get: [],
      post: []
    };
  }

  register() {
    let info = {};
    if (typeof arguments[0] === "string") {
      info.path = arguments[0];
      info.stack = slice.call(arguments, 1);
    } else {
      info.path = "/";
      info.stack = slice.call(arguments, 0);
    }
    return info;
  }
  use() {
    let result = this.register.apply(this, arguments);
    this.routes.all.push(result);
    console.log('all', this.routes.all)
  }
  get() {
    let result = this.register.apply(this, arguments);
    this.routes.get.push(result);
  }
  post() {
    let result = this.register.apply(this, arguments);
    this.routes.post.push(result);
  }
  match(method, url) {
    
    let resultList = [];
    let stack = [];
    stack = stack.concat(this.routes.all);
    stack = stack.concat(this.routes[method]);
    if (url === "favicon.icon") {
      return resultList;
    }
    for (let item of stack) {
      if (item.path.indexOf(url) === 0) {
        resultList = resultList.concat(item.stack);
      }
    }
    console.log('resut', resultList)
    return resultList;
  }
  handler(req, res, list) {
    const next = () => {
      let middleware = list.shift();
      if (typeof middleware === 'function') {
        middleware(req, res, next);
      }
    };
    next();
  }
  callback() {
    return (req, res) => {
      res.json = (data) => {
        res.setHeader("Content-type", "application/json");
        res.end(JSON.stringify(data));
      };
      let url = req.url;
      let method = req.method.toLowerCase();
      let resultList = this.match(method, url);
      console.log('list', resultList)
      this.handler(req, res, resultList);
    };
  }
  listen(...args) {
    let server = http.createServer(this.callback());
    server.listen(...args);
  }
}

module.exports = () => {
  return new LikeExpress();
};

// 简单koa2实现 主要是promise对象的包装
const http = require("http");

// 组合中间件
function compose(middlewareList) {
    return function(ctx) {
        function dispath(i) {
           const fn = middlewareList[i]
           try {
               return Promise.resolve(
                   fn(ctx, dispath.bind(null, i+1))
               )
           } catch (err) {
               return Promise.reject(err)
           }
        }
        return dispath(0)
    }
}
class LikeKoa2 {
  constructor() {
    this.middlewareList = [];
  }

  use(fn) {
    this.middlewareList.push(fn);
    return this;
  }
  createContent(req, res) {
      const ctx = {
          req, res
      }
      ctx.query = req.query
      return ctx
  }
  handler(ctx, fn) {
      return fn(ctx)
  }
  callback() {
      const fn = compose(this.middlewareList)
      return (req, res, next)=> {
         const ctx = this.createContent(req, res)
         return this.handler(ctx, fn)
      }
  }
  listen(...args) {
    let server = http.createServer(this.callback());
    server.listen(...args);
  }
}

module.exports = () =>{
    return new LikeKoa2()
}


上一篇 下一篇

猜你喜欢

热点阅读