What is koa-convert?
The koa-convert npm package is designed to help transition from Koa's old middleware signature (generator functions) to the new middleware signature (async functions). It wraps Koa's old generator-based middleware to be compatible with the new Koa v2.x async middleware signature. This allows developers to use legacy middleware that hasn't yet been updated to the new format, facilitating a smoother upgrade path to Koa v2.x.
What are koa-convert's main functionalities?
Converting generator-based middleware
This feature allows you to wrap old Koa middleware that uses generator functions into a form that's compatible with Koa v2.x's async middleware. The code sample demonstrates how to convert a simple timing middleware to the new format.
const convert = require('koa-convert');
const oldMiddleware = function *(next) {
const start = new Date;
yield next;
const ms = new Date - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
};
app.use(convert(oldMiddleware));
Other packages similar to koa-convert
koa-compose
koa-compose is a package for composing Koa middleware. While it doesn't directly convert middleware from the old to the new format, it's useful for managing middleware in Koa applications, especially when dealing with async functions. It complements koa-convert by providing a structured way to combine multiple middleware functions into a single middleware.
koa-adapter
koa-adapter is another package that aims to provide compatibility layers for Koa middleware, though it's less focused on converting from the old generator-based middleware to the new async-based middleware. Instead, it focuses on adapting Express middleware to be used in Koa applications, serving a slightly different but related purpose to koa-convert.
koa-convert
Convert koa generator-based middleware to promise-based middleware.
Installation
$ npm install koa-convert
Related Issues
Usage
const convert = require('koa-convert')
let promiseBased = convert(function* generatorBased(next) {
yield next
})
let mws = [
function* generatorMW (next) {
yield next
},
function* generatorMW(next) {
yield* next
},
function (ctx, next) {
return next()
},
async function (ctx, next) {
await next()
},
].map(convert)
License
MIT