Koa usage:

const Koa =require('koa');
const app=new Koa()
app.use((ctx,next)=>{
  ctx.body={
      name:123
  }
})
app.listen(3000,()=>{
     console.log('koa...')
})
Copy the code

Analysis of the

1. CTX relates to context, getter, setter 2. Next relates to the composition function composeCopy the code

request.js

module.exports = { 
    get url() {
      return this.req.url; 
    },
    get method(){
      return this.req.method.toLowerCase() 
    }
 };
Copy the code

response.js

module.exports = { get body() { return this._body; }, set body(val) { this._body = val; // Internal variable}};Copy the code

context.js

module.exports = { 
    get url() {
      return this.request.url; 
    },
    get body() {
      return this.response.body;
    },
    set body(val) {
      this.response.body = val; 
    },
    get method() {
       return this.request.method
    } 
};
Copy the code

compose.js

Function compose(middlewares){return function(CTX){return dispatch(0); function dispatch(i){ let fn=middlewares[i] if(! fn){Promise.resolve()} Promise.resolve( fn(ctx,function next(){ return dispatch(i+1) }) ) } } }Copy the code

koa.js

class Kkb{ constructor(){ this.middlewares = [] } listen(... Args){const server= http.createserver (async (req,res)=>{// createContext let CTX = this.createcontext (req,res); const fn = this.compose(this.middlewares) await fn(ctx) res.end(ctx.body); }) server.listen(... args) } use(middleware){ this.middlewares.push(middleware) } createContext(req,res){ const CTX = object.create (context)// use this.request CTX. Request = object.create (request)// Use native req Ctx.response = object.create (response) ctx.req=ctx.request. Req =req Compose (middlewares){return function(CTX){return CTX dispatch(0); function dispatch(i){ let fn=middlewares[i] if(! fn){Promise.resolve()} Promise.resolve( fn(ctx,function next(){ return dispatch(i+1) }) ) } } } }Copy the code

This is basically koA

Diagram of context connection: