This repository has been archived by the owner on Aug 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
105 lines (86 loc) · 2.02 KB
/
index.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict'
/**
* Module dependencies.
*/
const co = require('co')
const compose = require('koa-compose')
/**
* Expose `convert()`.
*/
module.exports = convert
/**
* Convert Koa legacy generator-based middleware
* to modern promise-based middleware.
*
*
* @api public
* */
function convert (mw) {
if (typeof mw !== 'function') {
throw new TypeError('middleware must be a function')
}
// assume it's Promise-based middleware
if (
mw.constructor.name !== 'GeneratorFunction' &&
mw.constructor.name !== 'AsyncGeneratorFunction'
) {
return mw
}
const converted = function (ctx, next) {
return co.call(
ctx,
mw.call(
ctx,
(function * (next) { return yield next() })(next)
))
}
converted._name = mw._name || mw.name
return converted
}
/**
* Convert and compose multiple middleware
* (could mix legacy and modern ones)
* and return modern promise middleware.
*
*
* @api public
* */
// 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 Koa modern promise-based middleware
* to legacy generator-based middleware.
*
*
* @api public
* */
convert.back = function (mw) {
if (typeof mw !== 'function') {
throw new TypeError('middleware must be a function')
}
// assume it's generator middleware
if (mw.constructor.name === 'GeneratorFunction' || mw.constructor.name === 'AsyncGeneratorFunction') {
return mw
}
const converted = function * (next) {
const ctx = this
let called = false
yield mw(ctx, function () {
if (called) {
// guard against multiple next() calls
// https://github.com/koajs/compose/blob/4e3e96baf58b817d71bd44a8c0d78bb42623aa95/index.js#L36
throw new Error('next() called multiple times')
}
called = true
return co.call(ctx, next)
})
}
converted._name = mw._name || mw.name
return converted
}