Handwriting koa2

A, koa2 core design

  1. Package node http server, creating class constructor Koa

  2. Construction request, response, and context object

  3. Middleware mechanism to achieve

Two, koa2 core code implementation

    1. main text matter koa.js

const http = require('http');const context = require('./context');const request = require('./request');const response = require('./response');class Koa {  constructor() {    this.middlewares = [];  }  listen(...args) {    http.createServer(async (req, res) => {      // 创建上下文对象      const ctx = this.createContext(req, res);      // 将middlewares合并成一个      const fn = this.compose(this.middlewares);      await fn(ctx);      // 给用户返回数据      res.end(ctx.body);    }).listen(...args);  }  use(mid) {    this.middlewares.push(mid);  }  createContext(req, res) {    const ctx = Object.create(context);    ctx.request = Object.create(request);    ctx.response = Object.create(response);    ctx.req = ctx.request.req = req;    ctx.res = ctx.response.res = res;    return ctx;    }  compose(middlewares) { // 中间件机制实现    return function(ctx) {      return dispatch(0); // 执行第0个      function dispatch(i) {        let fn = middlewares[i];        if (!fn) {          return Promise.resolve();        }        return Promise.resolve(          fn(ctx, function next() {            // promise完成后,再执行下一个            return dispatch(i + 1);                    });        )         }    }  }}

    2, the package request: request.js

module.exports = {  get url() {    return this.req.url;  }}

 

    3, the package response: response.js

module.exports = {  get body() {    return this._body;  }  set body(val) {    this._body = val;    }}

 

    4, the package context: context.js

module.exports = {  get url() {    return this.request.url;  }  get body() {    return this.response.body;  }  set body(val) {    this.response.body = val;  }}

 

Koa2 above is implemented as the core of the principles used only as a learning and understanding the core practice of koa2 more detailed implementation, specific inspection https://github.com/koajs/koa/tree/master/lib.

 

 

Reference material

  1. https://study.miaov.com/study/show/chapter/639

 

Micro-channel public number "front end that thing."

 

 

 

 

Published 71 original articles · won praise 43 · views 790 000 +

Guess you like

Origin blog.csdn.net/cengjingcanghai123/article/details/104578287