-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
89 lines (81 loc) · 1.73 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
/**
* ///////////////////////////////////////
* ////////// Middleware chain //////////
* ///////////////////////////////////////
*
* This module exposes the interface of
* the middleware chain.
*/
/**
* The chain constructor.
* @constructor
*/
const Chain = function () {
this.chain = [];
this.errorChain = [];
};
/**
* Pushes a function to the associated
* array given its arity.
* @param f the function to push
*/
const push = function (f) {
if (f.length === 4) {
this.errorChain.push(f);
} else {
this.chain.push(f);
}
};
/**
* Pushes a middleware, or a collection of
* middleware into the chain.
* @returns {Chain}
*/
Chain.prototype.use = function (...args) {
args.forEach((f) => {
if (typeof f === 'function') {
push.call(this, f);
} else if (Array.isArray(f)) {
f.forEach((value) => push.call(this, value));
}
});
return (this);
};
/**
* Triggers a new treatment to be processed by
* the chain.
* @param input
* @param output
*/
Chain.prototype.handle = function (input, output) {
let index = 0;
let errIndex = 0;
let chain = this.chain;
const callback = (chain, value) => {
let nextFunction;
if (chain === this.chain) {
nextFunction = chain[index++];
if (nextFunction) {
nextFunction(input, output, next);
}
} else if (chain === this.errorChain) {
nextFunction = chain[errIndex++];
if (nextFunction) {
nextFunction(value, input, output, next);
}
}
};
const next = (value) => {
if (value instanceof Error) {
chain = this.errorChain;
}
try {
callback(chain, value);
} catch (e) {
chain = this.errorChain;
callback(chain, e);
}
};
next();
};
export default Chain;