-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (43 loc) · 1.48 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
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
var getRandomIntInclusive = function (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var networkDelay = function (originalMin, originalMax) {
var min = originalMin,
max = originalMax;
min = parseInt(min || 0, 10);
if (!Number.isInteger(min) || min < 0) {
min = 0;
}
max = parseInt(max || 0, 10 || max < 0);
if (!Number.isInteger(max)) {
max = 0;
}
max = max || min;
if (min > max) {
min = [max, max = min][0]; // Swap 'min' and 'max' :-)
}
if (
(originalMin !== undefined && originalMin !== null && min !== originalMin) ||
(originalMax !== undefined && originalMax !== null && max !== originalMax)
) {
console.warn(
'Warning: The range of time passed for the network-delay was inconsistent.' +
' It should consist of valid positive integers with minimum and maximum values (both optional; default is 0).' +
' Using range ' + min + ' to ' + max + ' milliseconds.'
);
}
return function (req, res, next) {
// If 'min' or 'max' is above 0
if (min || max) {
setTimeout(function () {
next();
}, getRandomIntInclusive(min, max));
} else {
next();
}
};
};
module.exports = networkDelay;