-
Notifications
You must be signed in to change notification settings - Fork 6
/
node_helper.js
59 lines (50 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
'use strict';
/* Magic Mirror
* Module: MMM-JsonValue
*
* By Chris Klinger, http://chrisklinger.de
* MIT Licensed.
*/
const NodeHelper = require('node_helper');
const fetch = require("node-fetch");
const jp = require('jsonpath');
module.exports = NodeHelper.create({
start: function() {
this.subscribers = {};
},
getData: function(instanceID) {
//console.log("getData("+ instanceID + ")");
var self = this;
var requester = self.subscribers[instanceID]
self.doCall(requester.config.apiBase, requester.config.method, requester.config.headers, function(response) {
self.sendSocketNotification("DATA", {instanceID: instanceID, data: self.parseData(response, requester.config.jsonPath)});
})
setTimeout(function() { self.getData(instanceID); }, requester.config.refreshInterval);
},
parseData: function(data, jsonPath) {
if (!jsonPath.startsWith("$")) {
jsonPath = "$." + jsonPath;
}
return jp.query(data, jsonPath);
},
doCall: function(urlToCall, httpMethod, httpHeaders, callback) {
var fetchOptions = { method: httpMethod, headers: httpHeaders };
fetch(urlToCall, fetchOptions)
.then(res => res.json())
.then(json => callback(json))
.catch(error => console.log(error));
},
socketNotificationReceived: function(notification, payload) {
var self = this;
var instanceID = payload.instanceID;
//console.log(instanceID);
//console.log(self.subscribers);
if (notification === 'CONFIG' && !(instanceID in self.subscribers)) {
self.subscribers[instanceID] = {};
self.subscribers[instanceID].config = payload;
self.sendSocketNotification("STARTED", {instanceID: instanceID, started: true});
self.getData(instanceID);
self.subscribers[instanceID].started = true;
}
}
});