-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (54 loc) · 1.41 KB
/
index.js
File metadata and controls
61 lines (54 loc) · 1.41 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
61
'use strict'
const Promise = require('any-promise')
const callMiddleware = require('koa-call-middleware')
/**
* Expose compositor.
*/
module.exports = compose
/**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {Array} middleware
* @return {Function}
* @api public
*/
function compose (middleware) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function (context, next) {
// last called middleware #
let index = -1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if (!fn) return Promise.resolve()
try {
if (fn) {
return Promise.resolve(callMiddleware(fn, context, function next () {
return dispatch(i + 1)
}))
} else {
if (next) {
return Promise.resolve(next())
} else {
return Promise.resolve()
}
}
} catch (err) {
return Promise.reject(err)
}
}
}
}