-
Notifications
You must be signed in to change notification settings - Fork 26
/
MonitorApp.js
112 lines (94 loc) · 2.62 KB
/
MonitorApp.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const MonitorClient = require('./MonitorClient');
const path = require('path');
const fs = require('fs');
const os = require('os');
// Error messages
const errorMessages = {
no_api_key: 'No API Key specified'
};
// Watching flag
let watching = false;
// Initialization flag
let initialized = false;
class MonitorApp {
/**
* Constructor has the same params as the monitorClient class constructor.
*
* @param {string} apiKey
* @param {object} options
* @returns {MonitorApp}
*/
constructor(apiKey, options = {}) {
if (!apiKey) {
throw new Error(errorMessages.no_api_key);
}
this.monitor = new MonitorClient(apiKey, options);
this.state = {
poolId: false
};
this.options = {
// Temporary file to save watching state
tmpFile: path.join(os.tmpdir(), 'monitorAppState.tmp'),
...options
};
this.restoreState();
}
/**
* Initializes the app and adds addresses to the pool.
*
* @param {array} addresses
*/
async init(addresses) {
if (initialized) return;
if (this.state.poolId === false) {
// Create a new pool
this.state.poolId = await this.monitor.createPool();
this.saveState();
}
this.monitor.credentials.poolId = this.state.poolId;
if (addresses && addresses.length) {
this.monitor.addAddresses(addresses);
}
initialized = true;
}
/**
* Saves the app state to a file
*/
saveState() {
fs.writeFileSync(this.options.tmpFile, JSON.stringify(this.state));
}
/**
* Restores the app state from a file.
*/
restoreState() {
if (fs.existsSync(this.options.tmpFile)) {
const data = fs.readFileSync(this.options.tmpFile);
this.state = JSON.parse(data);
}
}
/**
* Starts watching for addresses changes.
* Will create a new pool if no poolId was stored in the watching state
*
* @param {function} callback
*/
async watch(callback) {
if (watching === true) return;
await this.init();
if (typeof (callback) === 'function') {
this.monitor.on('data', callback);
}
this.monitor.on('stateChanged', () => this.saveState);
this.monitor.watch();
watching = true;
}
/**
* Stops watching and removes listeners
*/
async unwatch() {
this.monitor.removeAllListeners();
this.monitor.unwatch();
watching = false;
}
}
module.exports = MonitorApp;