此係列文章的應用示例已發佈於 GitHub: koa-docs-Zh-CN. 能夠 Fork 幫助改進或 Star 關注更新. 歡迎 Star.git
Koa v2 引入了新的中間件簽名。es6
舊簽名中間件(v1.x)支持將在 v3 中刪除github
新的中間件簽名是這樣的:npm
// 使用異步箭頭方法 app.use(async (ctx, next) => { try { await next() // next 如今是一個方法 } catch (err) { ctx.body = { message: err.message } ctx.status = err.status || 500 } }) app.use(async ctx => { const user = await User.getById(this.session.userid) // await 替換了 yield ctx.body = user // ctx 替換了 this })
你沒必要必定使用異步函數 - 你只須要傳遞一個返回 promise 的函數。返回 promise 的常規方法也可使用!promise
簽名已更改成經過 ctx
取代 this
顯式參數傳遞 Context
。session
上下文傳遞更改使得 koa 更能兼容 es6 的箭頭函數,經過捕獲 「this」。app
Koa v2.x將嘗試轉換 app.use
上的舊簽名,生成器中間件, 使用 koa-convert.
不過建議您選擇儘快遷移全部 v1.x 中間件。koa
// Koa 將轉換 app.use(function *(next) { const start = Date.now(); yield next; const ms = Date.now() - start; console.log(`${this.method} ${this.url} - ${ms}ms`); });
您也能夠手動執行,在這種狀況下,Koa不會轉換。異步
const convert = require('koa-convert'); app.use(convert(function *(next) { const start = Date.now(); yield next; const ms = Date.now() - start; console.log(`${this.method} ${this.url} - ${ms}ms`); }));
您將不得不使用新的中間件簽名將您的生成器轉換爲異步功能:async
app.use(async (ctx, next) => { const user = await Users.getById(this.session.user_id); await next(); ctx.body = { message: 'some message' }; })
升級中間件可能須要一些工做。 一個遷移方式是逐個更新它們。
koa-convert
中npm outdated
看看哪一個 koa 中間件已通過時了koa-convert
刪除您應該開始重構代碼,以便輕鬆遷移到 Koa v2:
yield*
不要使用 yield {}
或 yield []
.
yield []
爲 yield Promise.all([])
yield {}
爲 yield Bluebird.props({})
您也能夠重構 Koa 中間件功能以外的邏輯。 建立一個方法像 function* someLogic(ctx) {}
而後在你的中間件中調用 const result = yield someLogic(this)
.
不使用 this
將有助於遷移到新的中間件簽名,因此不使用 this
。
在 v1.x 中,能夠直接調用應用構造函數,而不用 new
實例化一個應用程序的實例。 例如:
var koa = require('koa'); var app = module.exports = koa();
v2.x 使用 es6 類,須要使用 new
關鍵字。
var koa = require('koa'); var app = module.exports = new koa();
對於 test
環境的顯式檢查從錯誤處理中刪除。
仍然支持 v1.x 分支,但應該不會獲得功能性更新。 除了此遷移指南外,文檔將針對最新版本。
若是您遇到本遷移指南未涉及的遷移相關問題,請考慮提交文檔提取請求。
若是這篇文章對您有幫助, 感謝 下方點贊 或 Star GitHub: koa-docs-Zh-CN 支持, 謝謝.