-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Middleware.js
89 lines (79 loc) · 1.79 KB
/
Middleware.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
'use strict'
/*
* japa
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Middleware {
constructor (context, bail, fnWrapper) {
this._context = context
this._bail = !!bail
this._fnWrapper = fnWrapper
this._stack = []
this.errorsStack = []
}
/**
* Rejects the error by making sure bail is true.
* Otherwise stacks error for later rejection
*
* @param {Number}
* @param {Object}
* @param {Function}
* @param {Function}
*/
_internalRejection (index, resolve, reject, error) {
if (this._bail) {
reject(error)
return
}
this.errorsStack.push(error)
resolve(this._dispatch(index + 1))
}
/**
* Dispatches each layer of the stack one
* by one.
*
* @param {Number}
* @return {Promise}
*/
_dispatch (index) {
if (index === this._stack.length) {
return Promise.resolve()
}
const fn = this._stack[index]
return new Promise((resolve, reject) => {
this._fnWrapper(fn)
.then(() => this._dispatch(index + 1))
.then(resolve)
.catch((error) => this._internalRejection.bind(this)(index, resolve, reject, error))
})
}
/**
* Returns the first promise from the stack
* or a blank promise if stack is empty.
*
* @param {Function}
* @return {Promise}
*/
_middleware (next) {
if (this._stack.length === 0) {
return Promise.resolve()
}
return this._dispatch(0)
}
/**
* Composes a middleware layer to be executed
* in sequence.
*
* @param {Array} stack
* @return {Fuction}
*/
compose (stack) {
this._stack = stack
return this._middleware.bind(this)
}
}
module.exports = Middleware