forked from alexyak/stocks
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnode_helper.js
64 lines (51 loc) · 1.72 KB
/
node_helper.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
/* Magic Mirror
* Module: stocks
*
* By Alex Yakhnin https://github.com/alexyak & Elan Trybuch https://github.com/elaniobro
* MIT Licensed.
*/
var NodeHelper = require('node_helper');
var request = require('request');
module.exports = NodeHelper.create({
start: function () {
console.log('MMM-stocks: started'); /*eslint-disable-line*/
},
getStocks: function (url) {
var self = this;
request({ url: url, method: 'GET' }, function (error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
self.sendSocketNotification('STOCKS_RESULT', result);
}
});
},
getStocksMulti: function (urls) {
var self = this;
var count = urls.length;
var counter = 0;
var stockResults = [];
urls.forEach(url => {
request({ url: url, method: 'GET' }, function (error, response, body) {
if (!error && response.statusCode == 200) {
stockResults.push(JSON.parse(body));
counter++;
if (counter == count - 1) {
self.sendSocketNotification('STOCKS_RESULT', stockResults);
}
} else {
var err = error;
throw new Error(err);
}
});
});
},
//Subclass socketNotificationReceived received.
socketNotificationReceived: function (notification, payload) {
if (notification === 'GET_STOCKS') {
this.getStocks(payload);
}
if (notification === 'GET_STOCKS_MULTI') {
this.getStocksMulti(payload);
}
}
});