-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode_helper.js
84 lines (78 loc) · 2.57 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
/* MagicMirror²
* Node Helper: MMM-OnThisDayWikiApi
*
* By Ryan Seeber
* MIT Licensed.
*/
const NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
// Subclass start method.
start() {
console.log("Started node_helper.js for MMM-OnThisDayWikiApi.");
},
socketNotificationReceived(notification, payload) {
console.log(
`${this.name} node helper received a socket notification: ${notification} - Payload: ${payload}`
);
if (notification === "ONTHISDAY_FETCH") {
this.wikiOnThisDayRequest(
payload.config.apiBase,
payload.config.language,
payload.config.feature,
payload.config.type,
payload.month,
payload.day
);
} else {
console.log(
`${this.name} node helper ERROR: received unknown notification.`
);
}
},
async wikiOnThisDayRequest(apiBase, language, feature, type, month, day) {
const self = this;
const url = `${apiBase}/${language}/${feature}/${type}/${month}/${day}`;
console.log(url);
try {
const response = await fetch(url, { method: "GET" });
if (response.ok) {
const wikiData = await response.json();
const items = wikiData[type];
if (items.length <= 0) {
console.log("OnThisDay-Fetcher: No items to broadcast yet.");
return;
}
console.log(`OnThisDay-Fetcher: Broadcasting ${items.length} items.`);
self.sendSocketNotification("ONTHISDAY_ITEMS", items);
} else if (response.status === 400) {
const errorMsg = "Invalid parameter";
console.error(errorMsg);
self.sendSocketNotification("ONTHISDAY_ERROR", {
error_type: errorMsg
});
} else if (response.status === 404) {
const errorMsg = "No data found for the requested date";
console.error(errorMsg);
self.sendSocketNotification("ONTHISDAY_ERROR", {
error_type: errorMsg
});
} else if (response.status === 501) {
const errorMsg = "Unsupported language";
console.error(errorMsg);
self.sendSocketNotification("ONTHISDAY_ERROR", {
error_type: errorMsg
});
} else {
const errorMsg = `Bad response from server: ${response.status}`;
console.error(errorMsg);
self.sendSocketNotification("ONTHISDAY_ERROR", {
error_type: errorMsg
});
}
} catch (error) {
const errorMsg = "Unknown error";
console.error(errorMsg, error);
self.sendSocketNotification("ONTHISDAY_ERROR", { error_type: errorMsg });
}
}
});