index.js
1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict'
const co = require('co')
const compose = require('koa-compose')
module.exports = convert
function convert (mw) {
if (typeof mw !== 'function') {
throw new TypeError('middleware must be a function')
}
if (mw.constructor.name !== 'GeneratorFunction') {
// assume it's Promise-based middleware
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()
}
// convert.compose(mw, mw, mw)
// convert.compose([mw, mw, mw])
convert.compose = function (arr) {
if (!Array.isArray(arr)) {
arr = Array.from(arguments)
}
return compose(arr.map(convert))
}
convert.back = function (mw) {
if (typeof mw !== 'function') {
throw new TypeError('middleware must be a function')
}
if (mw.constructor.name === 'GeneratorFunction') {
// assume it's generator middleware
return mw
}
const converted = function * (next) {
let ctx = this
let called = false
// no need try...catch here, it's ok even `mw()` throw exception
yield Promise.resolve(mw(ctx, function () {
if (called) {
// guard against multiple next() calls
// https://github.com/koajs/compose/blob/4e3e96baf58b817d71bd44a8c0d78bb42623aa95/index.js#L36
return Promise.reject(new Error('next() called multiple times'))
}
called = true
return co.call(ctx, next)
}))
}
converted._name = mw._name || mw.name
return converted
}