koa

const http = require("http"); // Combine middlewarefunction compose(middlewareList) {
  return function(ctx) {
    function dispatch(i) {
      const fn = middlewareList[i];
      try {
        return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1)));
      } catch (err) {
        returnPromise.reject(err); }}return dispatch(0);
  };
}
class LikeKoa2 {
  constructor() { this.middlewareList = []; } // Use (fn) {this.middlewareList.push(fn);returnthis; } // Handle HTTP requests for middleware handleRequest(CTX, MiddleWare) {// This middleWare is the fn returned by the compose functionreturnmiddleWare(ctx); Const CTX = {req, res}; const CTX = {req, res}; const CTX = {req, res};return ctx;
  }

  callback() {
    const fn = compose(this.middlewareList);

    return (req, res) => {
      const ctx = this.createContext(req, res);
      returnthis.handleRequest(ctx, fn); }; } listen(... args) { const server = http.createServer(this.callback());returnserver.listen(... args); } } module.exports = LikeKoa2;Copy the code

test

const Koa = require('./myKoa.js'); const app = new Koa(); // logger app.use(async (ctx, next) => { await next(); const rt = ctx['X-Response-Time'];
  console.log(`${ctx.req.method} ${ctx.req.url} - ${rt}`);
});
  
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx['X-Response-Time'] = `${ms}ms`; }); // app.use(async ctx => { ctx.res.end('hello world')}); app.listen(8000);Copy the code