-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
61 lines (49 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
51
52
53
54
55
56
57
58
59
60
61
'use strict';
const EventEmitter = require('events');
// options (defaults)
// minPing (1): minimum number of pings to receive between check intervals
// checkInterval (10000): interval (in ms) between checks
// stopOnError (true): when true the checks will stop after the first failed check
class Watchpuppy extends EventEmitter {
constructor(options, callback) {
super();
if (typeof options === 'function') {
callback = options;
options = {};
}
this.minPing = options.minPing || 1;
this.checkInterval = options.checkInterval || 10000;
this.stopOnError = options.stopOnError !== false;
//internal properties
this.counter = 0;
this.interval = setInterval(() => this.emit('check'), this.checkInterval);
//setup listeners
this.on('ping', function() {
this.counter++;
});
this.on('check', function() {
if (this.counter < this.minPing) {
//something is wrong. emit error
this.emit('error', new Error(`only ${this.counter} pings received since last check`));
}
this.counter = 0;
});
this.on('error', function(err) {
if (this.stopOnError) {
this.stop();
}
callback(err);
});
}
//it is possible to give more weight to a ping or disable it by passing in a negative number
ping(num) {
num = 1 * num || 1;
for (let i = 0; i < num; i++) {
this.emit('ping');
}
}
stop() {
clearInterval(this.interval);
}
}
module.exports = Watchpuppy;