koa-convert
Convert Koa legacy (0.x & 1.x) generator middleware to modern promise middleware (2.x).
It could also convert modern promise middleware back to legacy generator middleware (useful to help modern middleware support Koa v0.x or v1.x).
Note
Router middleware is special case here. Because it reimplements middleware composition internally, we cannot not simply convert it.
You may use following packages for routing, which are koa 2.x ready now:
Installation
# npm .. $ npm i koa-convert# yarn .. $ yarn add koa-convert
Usage
const Koa = // koa v2.xconst convert = const app = app app app { // before next // after} { // before return }
Distinguish legacy and modern middleware
In koa 0.x and 1.x (without experimental flag), app.use
has an assertion that all (legacy) middleware must be generator function and it's tested with fn.constructor.name == 'GeneratorFunction'
at here.
Therefore, we can distinguish legacy and modern middleware with fn.constructor.name == 'GeneratorFunction'
.
Migration
app.use(legacyMiddleware)
is everywhere in 0.x and 1.x and it would be painful to manually change all of them to app.use(convert(legacyMiddleware))
.
You can use following snippet to make migration easier.
const _use = appuseapp _use
The above snippet will override app.use
method and implicitly convert all legacy generator middleware to modern promise middleware.
Therefore, you can have both app.use(modernMiddleware)
and app.use(legacyMiddleware)
and your 0.x or 1.x should work without modification.
Complete example:
const Koa = // v2.xconst convert = const app = // ---------- override app.use method ---------- const _use = appuseapp _use // ---------- end ---------- app // this will be converted to modern promise middleware implicitlyapp { // before next // after} { // before return }
API
convert()
Convert legacy generator middleware to modern promise middleware.
modernMiddleware =
convert.compose()
Convert and compose multiple middleware (could mix legacy and modern ones) and return modern promise middleware.
composedModernMiddleware = convert// orcomposedModernMiddleware = convert
convert.back()
Convert modern promise middleware back to legacy generator middleware.
This is useful to help modern promise middleware support koa 0.x or 1.x.
legacyMiddleware = convert