关于koa:Koa入门教程5升级为Koa2

28次阅读

共计 2152 个字符,预计需要花费 6 分钟才能阅读完成。

先来翻译一波 官网的 migration 指南:

从 Koa v1.x 迁徙到 v2.x

新的中间件函数签名

Koa v2 引入了一个新的中间件签名

老的中间件签名形式 (v1.x) 将在 v3 版本删除

新的 middleware 签名如下:

// 用 async 箭头函数
app.use(async (ctx, next) => {
  try {await next() // next 不再是 generator 迭代器,而是一个 asycn 函数了
  } 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
})

你不是只能用 async 函数 - 你只须要保障传递一个返回 promise 的函数
一个一般返回 promise 的函数照样能够工作。

这个中间件函数签名改成了传入一个严格的 ctx 参数 (Context 对象),而不是用 this 来拜访以后申请上下文. 这个扭转使得 koa 更能兼容 es6 箭头函数捕捉 this.

在 v2.x 中应用 v1.x 的中间件

Koa v2.x 在调用 app.use 的时候能够兼容 generator 的 middleware,它应用 koa-convert. 来干这件事。
然而还是倡议你连忙迁徙这些 v1 的中间件。

// Koa 会转换这种 generator 中间件
app.use(function *(next) {const start = Date.now();
  yield next;
  const ms = Date.now() - start;
  console.log(`${this.method} ${this.url} - ${ms}ms`);
});

你也能够手工转换本人的中间件,这样 app.use 外面就不会再转换了。

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'};
})

降级中间件须要一些工作量,一个比拟好的迁徙门路是 一个个的来

  1. 先用 koa-convert 包裹你当初的 v1 版本的中间件
  2. 测试是否失常
  3. 执行npm outdated 看看你依赖的第三方中间件有哪些过期了
  4. 依照下面讲的降级你的中间件,而后移除掉 koa-convert 的包裹
  5. 测试是否失常
  6. 一直反复 1 - 5 降级所有中间件

降级你的代码

迁徙到 Koa v2 你可能也要降级本人的业务代码:

  • 在任何异步的中央都返回 promise!
  • 不要再用 yield*
  • 不要再用 yield {} or yield [].

    • yield [] 换成 yield Promise.all([])
    • yield {} 换成 yield Bluebird.props({})

你也能够重构你的中间件以外的逻辑代码函数,例如写成接管 ctx 上下文参数的这种:
function* someLogic(ctx) {}
这样在你 v1 的 koa 的中间件里这样调用:
const result = yield someLogic(this).
先放弃应用 this 能够帮忙你将来迁徙到 v2 外面不必 this 的状况。

Application 构造函数必须应用 new 运算符

在 v1.x 里,Application 构造函数能够间接调用来实例化,例如:

var koa = require('koa');
var app = module.exports = koa();

v2.x 外面构造函数用了 es6 的 class,必须应用 new 关键字

var koa = require('koa');
var app = module.exports = new koa();

ENV 指定日志行为的环境变量被移除了

错误处理时对 test 环境变量的严格查看被移除了

依赖变动

  • co 曾经不是内置在 koa 外面了(因为不须要了)。如果你须要,则须要本人引入。
  • composition is 这个 compose 中间件的函数曾经废除了。Koa2 用的是 koa-compose

v1.x 的反对

The v1.x branch is still supported but should not receive feature updates. Except for this migration
guide, documentation will target the latest version.
v1.x 分支还会持续反对,但不会再减少新的 feature。除了这个迁徙文档,默认的官网文档都指向 v2 的

帮忙

如果你遇到迁徙的其余问题,能够提交 pull request

todo-list 利用的降级

// TODO

正文完
 0