-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode_helper.js
131 lines (110 loc) · 2.86 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* Magic Mirror
* Node Helper: MMM-CTA
*
* By Jordan Welch
* MIT Licensed.
*/
const Log = require('logger');
const NodeHelper = require('node_helper');
module.exports = NodeHelper.create({
socketNotificationReceived (notification, payload) {
if (notification !== 'MMM-CTA-FETCH') {
return;
}
if (!this.validate(payload)) {
return;
}
this.getData(payload);
},
async getData ({
trainApiKey,
busApiKey,
maxResultsTrain,
maxResultsBus,
stops,
}) {
const responses = await Promise.all(stops.map(async (stop) => {
if (stop.type === 'train') {
return {
type: 'train',
name: stop.name,
arrivals: await this.getTrainData(
stop.id,
maxResultsTrain,
trainApiKey,
),
};
}
return {
type: 'bus',
name: stop.name,
arrivals: await this.getBusData(
stop.id,
maxResultsBus,
busApiKey,
),
};
}));
this.sendSocketNotification('MMM-CTA-DATA', {
stops: responses.flat(),
});
},
async getBusData (id, maxResults, apiKey) {
const response = await fetch(this.busUrl(id, maxResults, apiKey));
const { 'bustime-response': data } = await response.json();
if (!data?.prd) {
return [];
}
return data.prd.map((bus) => ({
route: bus.rt,
direction: bus.rtdir,
arrival: bus.prdctdn,
}));
},
async getTrainData (id, maxResults, apiKey) {
const response = await fetch(this.trainUrl(id, maxResults, apiKey));
const { ctatt: data } = await response.json();
if (!data?.eta) {
return [];
}
return data.eta.map((train) => ({
direction: train.destNm,
routeColor: this.routeToColor(train.rt),
time: new Date(train.arrT),
}));
},
validate (payload) {
const required = [/** TODO: Add Required */];
return this.validateRequired(payload, required);
},
validateRequired (payload, required) {
let valid = true;
required.forEach((req) => {
if (!payload[req]) {
Log.error(`MMM-CTA: Missing ${req} in config`);
valid = false;
}
});
return valid;
},
busUrl (id, maxResults, apiKey) {
const baseUrl = 'http://www.ctabustracker.com/bustime/api/v2/getpredictions';
return `${baseUrl}?key=${apiKey}&stpid=${id}&top=${maxResults}&format=json`;
},
trainUrl (id, maxResults, apiKey) {
const baseUrl = 'http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx';
return `${baseUrl}?key=${apiKey}&mapid=${id}&max=${maxResults}&outputType=json`; // eslint-disable-line @stylistic/max-len
},
routeToColor (route) {
return {
Red: 'red',
Blue: 'blue',
Brn: 'brown',
G: 'green',
Org: 'orange',
P: 'purple',
Pink: 'pink',
Y: 'yellow',
}[route] || 'gray';
},
});