Analysis of the realization principle of Koa2 middleware in node JS

One, koa2

  1. koa2,As follows:
  • expressMiddleware is asynchronous callback, koa2native supportasync/await
  • New development frameworks and systems are beginning to be based on koa2, for exampleegg.js
  • expressAlthough not dated, but koa2certainly is the future trend
  1. asyncAnd awaitpoints:
  • awaitCan be followed by promisean object, acquires resolvea value
  • awaitYou must be wrapped in asynca function inside
  • asyncAlso function executes a return of promiseobjects
  • try-catchIntercepted promisein rejectvalue
  1. koa2 The internal principle of middleware realization, the code is as follows:
const http = require('http')

// 组合中间件
function compose(middlewareList) {
    
    
  return function (ctx) {
    
    
    function dispatch(i) {
    
    
      const fn = middlewareList[i]
      try {
    
    
        return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1))) // promise 对象
      } catch (err) {
    
    
        return Promise.reject(err)
      }
    }
    return dispatch(0)
  }
}


class LikeKoa2 {
    
    
  constructor () {
    
    
    this.middlewareList = []
  }

  use (fn) {
    
    
    this.middlewareList.push(fn)
    return this
  }

  createContext (req, res) {
    
    
    const ctx = {
    
    
      req,
      res
    }
    ctx.query = req.query
    return ctx
  }

  handleRequest (ctx, fn) {
    
    
    return fn(ctx)
  }

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

    return (req, res)  => {
    
    
      const ctx = this.createContext(req, res)
      return this.handleRequest(ctx, fn)
    }
  }

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

module.exports = LikeKoa2

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/110944334