koa源碼閱讀[0]

koa源碼閱讀[0]

Node.js也是寫了兩三年的時間了,剛開始學習Node的時候,hello world就是建立一個HttpServer,後來在工做中也是經歷過ExpressKoa1.xKoa2.x以及最近還在研究的結合着TypeScriptrouting-controllers(驅動依然是ExpressKoa)。
用的比較多的仍是Koa版本,也是對它的洋蔥模型比較感興趣,因此最近抽出時間來閱讀其源碼,正好近期可能會對一個Express項目進行重構,將其重構爲koa2.x版本的,因此,閱讀其源碼對於重構也是一種有效的幫助。node

Koa是怎麼來的

首先須要肯定,Koa是什麼。
任何一個框架的出現都是爲了解決問題,而Koa則是爲了更方便的構建http服務而出現的。
能夠簡單的理解爲一個HTTP服務的中間件框架。git

使用http模塊建立http服務

相信你們在學習Node時,應該都寫過相似這樣的代碼:github

const http = require('http')

const serverHandler = (request, response) => {
  response.end('Hello World') // 返回數據
}

http
  .createServer(serverHandler)
  .listen(8888, _ => console.log('Server run as http://127.0.0.1:8888'))

 

一個最簡單的示例,腳本運行後訪問http://127.0.0.1:8888便可看到一個Hello World的字符串。
可是這僅僅是一個簡單的示例,由於咱們無論訪問什麼地址(甚至修改請求的Method),都老是會獲取到這個字符串:promise

> curl http://127.0.0.1:8888
> curl http://127.0.0.1:8888/sub
> curl -X POST http://127.0.0.1:8888

 

因此咱們可能會在回調中添加邏輯,根據路徑、Method來返回給用戶對應的數據:app

const serverHandler = (request, response) => {
  // default
  let responseData = '404'

  if (request.url === '/') {
    if (request.method === 'GET') {
      responseData = 'Hello World'
    } else if (request.method === 'POST') {
      responseData = 'Hello World With POST'
    }
  } else if (request.url === '/sub') {
    responseData = 'sub page'
  }

  response.end(responseData) // 返回數據
}

 

相似Express的實現

可是這樣的寫法還會帶來另外一個問題,若是是一個很大的項目,存在N多的接口。
若是都寫在這一個handler裏邊去,未免太過難以維護。
示例只是簡單的針對一個變量進行賦值,可是真實的項目不會有這麼簡單的邏輯存在的。
因此,咱們針對handler進行一次抽象,讓咱們可以方便的管理路徑:框架

class App {
  constructor() {
    this.handlers = {}

    this.get = this.route.bind(this, 'GET')
    this.post = this.route.bind(this, 'POST')
  }

  route(method, path, handler) {
    let pathInfo = (this.handlers[path] = this.handlers[path] || {})

    // register handler
    pathInfo[method] = handler
  }

  callback() {
    return (request, response) => {
      let { url: path, method } = request

      this.handlers[path] && this.handlers[path][method]
        ? this.handlers[path][method](request, response)
        : response.end('404')
    }
  }
}

 

而後經過實例化一個Router對象進行註冊對應的路徑,最後啓動服務:koa

const app = new App()

app.get('/', function (request, response) {
  response.end('Hello World')
})

app.post('/', function (request, response) {
  response.end('Hello World With POST')
})

app.get('/sub', function (request, response) {
  response.end('sub page')
})

http
  .createServer(app.callback())
  .listen(8888, _ => console.log('Server run as http://127.0.0.1:8888'))

 

Express中的中間件

這樣,就實現了一個代碼比較整潔的HttpServer,但功能上依舊是很簡陋的。
若是咱們如今有一個需求,要在部分請求的前邊添加一些參數的生成,好比一個請求的惟一ID。
將代碼重複編寫在咱們的handler中確定是不可取的。
因此咱們要針對route的處理進行優化,使其支持傳入多個handlercurl

route(method, path, ...handler) {
  let pathInfo = (this.handlers[path] = this.handlers[path] || {})

  // register handler
  pathInfo[method] = handler
}

callback() {
  return (request, response) => {
    let { url: path, method } = request

    let handlers = this.handlers[path] && this.handlers[path][method]

    if (handlers) {
      let context = {}
      function next(handlers, index = 0) {
        handlers[index] &&
          handlers[index].call(context, request, response, () =>
            next(handlers, index + 1)
          )
      }

      next(handlers)
    } else {
      response.end('404')
    }
  }
}

 

而後針對上邊的路徑監聽添加其餘的handler:異步

function generatorId(request, response, next) {
  this.id = 123
  next()
}

app.get('/', generatorId, function(request, response) {
  response.end(`Hello World ${this.id}`)
})

 

這樣在訪問接口時,就能夠看到Hello World 123的字樣了。
這個就能夠簡單的認爲是在Express中實現的 中間件
中間件是ExpressKoa的核心所在,一切依賴都經過中間件來進行加載。async

更靈活的中間件方案-洋蔥模型

上述方案的確可讓人很方便的使用一些中間件,在流程控制中調用next()來進入下一個環節,整個流程變得很清晰。
可是依然存在一些侷限性。
例如若是咱們須要進行一些接口的耗時統計,在Express有這麼幾種能夠實現的方案:

function beforeRequest(request, response, next) {
  this.requestTime = new Date().valueOf()

  next()
}

// 方案1. 修改原handler處理邏輯,進行耗時的統計,而後end發送數據
app.get('/a', beforeRequest, function(request, response) {
  // 請求耗時的統計
  console.log(
    `${request.url} duration: ${new Date().valueOf() - this.requestTime}`
  )

  response.end('XXX')
})

// 方案2. 將輸出數據的邏輯挪到一個後置的中間件中
function afterRequest(request, response, next) {
  // 請求耗時的統計
  console.log(
    `${request.url} duration: ${new Date().valueOf() - this.requestTime}`
  )

  response.end(this.body)
}

app.get(
  '/b',
  beforeRequest,
  function(request, response, next) {
    this.body = 'XXX'

    next() // 記得調用,否則中間件在這裏就終止了
  },
  afterRequest
)

 

不管是哪種方案,對於原有代碼都是一種破壞性的修改,這是不可取的。
由於Express採用了response.end()的方式來向接口請求方返回數據,調用後即會終止後續代碼的執行。
並且由於當時沒有一個很好的方案去等待某個中間件中的異步函數的執行。

function a(_, _, next) {
  console.log('before a')
  let results = next()
  console.log('after a')
}

function b(_, _, next) {
  console.log('before b')
  setTimeout(_ => {
    this.body = 123456
    next()
  }, 1000)
}

function c(_, response) {
  console.log('before c')
  response.end(this.body)
}

app.get('/', a, b, c)

 

就像上述的示例,實際上log的輸出順序爲:

before a
before b
after a
before c

 

這顯然不符合咱們的預期,因此在Express中獲取next()的返回值是沒有意義的。

因此就有了Koa帶來的洋蔥模型,在Koa1.x出現的時間,正好遇上了Node支持了新的語法,Generator函數及Promise的定義。
因此纔有了co這樣使人驚歎的庫,而當咱們的中間件使用了Promise之後,前一箇中間件就能夠很輕易的在後續代碼執行完畢後再處理本身的事情。
可是,Generator自己的做用並非用來幫助咱們更輕鬆的使用Promise來作異步流程的控制。
因此,隨着Node7.6版本的發出,支持了asyncawait語法,社區也推出了Koa2.x,使用async語法替換以前的co+Generator

Koa也將co從依賴中移除(2.x版本使用koa-convertGenerator函數轉換爲promise,在3.x版本中將直接不支持Generator
ref: remove generator supports

因爲在功能、使用上Koa的兩個版本之間並無什麼區別,最多就是一些語法的調整,因此會直接跳過一些Koa1.x相關的東西,直奔主題。

Koa中,可使用以下的方式來定義中間件並使用:

async function log(ctx, next) {
  let requestTime = new Date().valueOf()
  await next()

  console.log(`${ctx.url} duration: ${new Date().valueOf() - requestTime}`)
}

router.get('/', log, ctx => {
  // do something...
})

 

由於一些語法糖的存在,遮蓋了代碼實際運行的過程,因此,咱們使用Promise來還原一下上述代碼:

function log() {
  return new Promise((resolve, reject) => {
    let requestTime = new Date().valueOf()
    next().then(_ => {
      console.log(`${ctx.url} duration: ${new Date().valueOf() - requestTime}`)
    }).then(resolve)
  })
}

 

大體代碼是這樣的,也就是說,調用next會給咱們返回一個Promise對象,而Promise什麼時候會resolve就是Koa內部作的處理。
能夠簡單的實現一下(關於上邊實現的App類,僅僅須要修改callback便可):

callback() {
  return (request, response) => {
    let { url: path, method } = request

    let handlers = this.handlers[path] && this.handlers[path][method]

    if (handlers) {
      let context = { url: request.url }
      function next(handlers, index = 0) {
        return new Promise((resolve, reject) => {
          if (!handlers[index]) return resolve()

          handlers[index](context, () => next(handlers, index + 1)).then(
            resolve,
            reject
          )
        })
      }

      next(handlers).then(_ => {
        // 結束請求
        response.end(context.body || '404')
      })
    } else {
      response.end('404')
    }
  }
}

 

每次調用中間件時就監聽then,並將當前Promiseresolvereject處理傳入Promise的回調中。
也就是說,只有當第二個中間件的resolve被調用時,第一個中間件的then回調纔會執行。
這樣就實現了一個洋蔥模型。

就像咱們的log中間件執行的流程:

  1. 獲取當前的時間戳requestTime
  2. 調用next()執行後續的中間件,並監聽其回調
  3. 第二個中間件裏邊可能會調用第三個、第四個、第五個,但這都不是log所關心的,log只關心第二個中間件什麼時候resolve,而第二個中間件的resolve則依賴他後邊的中間件的resolve
  4. 等到第二個中間件resolve,這就意味着後續沒有其餘的中間件在執行了(全都resolve了),此時log纔會繼續後續代碼的執行

因此就像洋蔥同樣一層一層的包裹,最外層是最大的,是最早執行的,也是最後執行的。(在一個完整的請求中,next以前最早執行,next以後最後執行)。

小記

最近抽時間將Koa相關的源碼翻看一波,看得挺激動的,想要將它們記錄下來。
應該會拆分爲幾段來,不一篇全寫了,上次寫了個裝飾器的,太長,看得本身都困了。
先佔幾個坑:

  • 核心模塊 koa與koa-compose
  • 熱門中間件 koa-router與koa-views
  • 雜七雜八的輪子 koa-bodyparser/multer/better-body/static

示例代碼倉庫地址
源碼閱讀倉庫地址

相關文章
相關標籤/搜索