-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
64 lines (58 loc) · 2.02 KB
/
node_helper.js
File metadata and controls
64 lines (58 loc) · 2.02 KB
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
/* Magic Mirror
* Node Helper: HTTPRequest
*
* By Andreas Cederström
* MIT Licensed.
*/
const NodeHelper = require("node_helper");
const request = require('request');
module.exports = NodeHelper.create({
// Subclass start method.
start: function() {
var self = this;
console.log("Starting node helper for: " + self.name);
this.loaded = false;
},
// Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
if (notification === 'HTTP_REQUEST_INIT') {
this.config = payload.config;
}
else if (notification === 'HTTP_REQUEST_SEND') {
this.sendRequest(payload.id);
}
},
sendRequest: function(id) {
var self = this;
var requestConfig = this.config.requests[id];
if (!requestConfig) {
console.error("Could not find request config for " + id);
return;
}
request({
url: requestConfig.url,
method: requestConfig.method || "GET",
auth: requestConfig.auth || null
}, function(error, response, body) {
if (!error && [200, 201, 202].indexOf(response.statusCode) >= 0) {
self.sendSocketNotification("HTTP_REQUEST_CALLBACK", {
notification: requestConfig.onSuccess.notification,
payload: requestConfig.onSuccess.payload
});
}
else {
console.error("Could not perform request " + id);
if (self.config.showAlertOnError) {
self.sendSocketNotification("HTTP_REQUEST_CALLBACK", {
notification: "SHOW_ALERT",
payload: {
title: "HTTP Status: " + response.statusCode,
message: this.responseText,
timer: 3000
}
});
}
}
});
}
});