Search code examples
javascriptnode.jskoakoa2koa-router

Migrating koa v1 to v2


I'm using some module with koa and they only have this documentation which is written in koa v1 not v2. and since I've never used v1 before, I have no idea how to write this in v2.

app
  .use(body({
    IncomingForm: form
  }))
  .use(function * () {
    console.log(this.body.user) // => test
    console.log(this.request.files) // or `this.body.files`
    console.log(this.body.files.foo.name) // => README.md
    console.log(this.body.files.foo.path) // => full filepath to where is uploaded
  })

Solution

  • Changing from Koa v1 to Koa v2 is a pretty simple process. The only reason for the version bump is that it uses async functions instead of generators for your middleware.

    Example v1 Middleware:

    app.use(function* (next) {
      yield next
      this.body = 'hello'
    })
    

    Example v2 Middleware:

    app.use(async (ctx, next) => {
      await next()
      ctx.body = 'hello'
    })
    

    use async functions instead of generators, and accept ctx as a parameter instead of using this.