-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
node_helper.js
102 lines (95 loc) · 3.11 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
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
const fetch = (...args) =>
import("node-fetch").then(({ default: fetch }) => fetch(...args));
var jp = require("jsonpath");
const { jq } = require("jq.node");
var NodeHelper = require("node_helper");
function asPromise(context, callbackFunction, ...args) {
return new Promise((resolve, reject) => {
args.push((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
if (context) {
callbackFunction.call(context, ...args);
} else {
callbackFunction(...args);
}
});
}
async function do_jq(filter, data) {
if (filter) {
try {
data = await asPromise(null, jq, JSON.stringify(data), filter, {});
data = JSON.parse(data);
console.debug("JQ Converted data: ", data);
} catch (e) {
console.error("Error handling jq.node filter '" + filter + "':", e);
}
}
return data;
}
module.exports = NodeHelper.create({
start: function () {
console.log("Starting node helper: " + this.name);
},
socketNotificationReceived: function (notification, payload) {
var self = this;
console.log("Notification: " + notification + " Payload:", payload);
if (notification === "MMM_JSON_REQUEST") {
fetch(payload.config.url, payload.config.fetchOptions)
.then(async (response) => {
// Success
console.debug(response);
if (Math.floor(response.status / 100) === 2) {
var responseObject;
jsonData = await do_jq(payload.config.jq, await response.json());
if (
payload.config.values == undefined ||
payload.config.values.length == 0
) {
// Values are not defined return all object properties
responseObject = {
identifier: payload.identifier,
data: Object.keys(jsonData).map((prop) => {
return { title: prop, value: [jsonData[prop]] };
})
};
} else {
// Values are defined, get what the user wants
responseObject = {
identifier: payload.identifier,
data: payload.config.values.map((val) => {
return {
...val,
value: (Array.isArray(val.query)
? val.query
: [val.query]
).map((query) => {
return val.numberDevisor != undefined
? (
jp.query(jsonData, query)[0] / val.numberDevisor
).toFixed(3)
: jp.query(jsonData, query)[0];
})
};
})
};
}
self.sendSocketNotification("MMM_JSON_RESPONSE", responseObject);
}
})
.catch((error) => {
console.error(error);
// Error
self.sendSocketNotification("MMM_JSON_RESPONSE", {
identifier: payload.identifier,
error: true
});
console.error(self.name + " error:", error);
});
}
}
});