Koa系列-Utilities:koa-convert
2019-04-15
字数统计:7.9k 字
阅读时长 ≈ 7 分钟
该中间件是用来转化 koa legacy
中间件。
convert
是用来将中间件(0.x & 1.x)转化为(2.x)
convert.back
是用来将中间件(2.x)转化为(0.x & 1.x)
convert.compose
是通过 koa-compose
来执行这些转化过的中间件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function convert (mw) { if (typeof mw !== 'function') { throw new TypeError('middleware must be a function') } if (mw.constructor.name !== 'GeneratorFunction') { return mw } const converted = function (ctx, next) { return co.call(ctx, mw.call(ctx, createGenerator(next))) } converted._name = mw._name || mw.name return converted }
function * createGenerator (next) { return yield next() }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| convert.back = function (mw) { if (typeof mw !== 'function') { throw new TypeError('middleware must be a function') } if (mw.constructor.name === 'GeneratorFunction') { return mw } const converted = function * (next) { let ctx = this let called = false if (called) { return Promise.reject(new Error('next() called multiple times')) } called = true return co.call(ctx, next) })) } converted._name = mw._name || mw.name return converted }
|
1 2 3 4 5 6 7
| convert.compose = function (arr) { if (!Array.isArray(arr)) { arr = Array.from(arguments) } return compose(arr.map(convert)) }
|