forked from Arve/MMM-Entur-tavle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
115 lines (103 loc) · 3.63 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
/* eslint-disable prettier/prettier */
const { response } = require("express");
let fetchPromise; // Use a promise to ensure proper initialization
async function initializeFetch() {
try {
const nodeFetch = await import("node-fetch");
fetchPromise = Promise.resolve(nodeFetch.default);
console.log("fetch is initialized");
} catch (error) {
console.error("Error importing 'node-fetch':", error);
}
}
// Initialize fetch when the module is loaded
initializeFetch();
const NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function(){
console.log("Starting node helper for: " + this.name);
},
getFullId: function(id, type, authority){
return `${authority}:${type}:${id}`;
},
prepareQuery: function(data){
let startTime = "";
let queryInit = "";
const fullId = this.getFullId(data.id, data.stopType, data.authorityId);
if (data.startTime) {
startTime = `startTime: "${data.startTime}", `;
}
if (data.stopType === "StopPlace"){
queryInit = `stopPlace(id: "${fullId}")`;
} else if (data.stopType === "Quay"){
queryInit = `quay (id: "${fullId}")`;
};
let whitelist = data.whiteListedTransportModes;
if (whitelist.length !== 0){
whitelist = `[${whitelist}]`; // example format: whiteListedModes: [tram,metro]
} else {
whitelist = null;
}
let $query = `{
${queryInit} {
id
name
estimatedCalls(${startTime}
timeRange: 72100
numberOfDepartures: ${data.numResults}
whiteListedModes: ${whitelist}
) {
aimedDepartureTime
expectedDepartureTime
actualDepartureTime
realtime
realtimeState
forBoarding
destinationDisplay {
frontText
}
serviceJourney {
journeyPattern {
line {
id
name
transportMode
publicCode
}
}
}
}
}
}`;
return $query;
},
socketNotificationReceived: async function(message, payload){
try {
// Wait for fetch to be initialized
const fetch = await fetchPromise;
const body = this.prepareQuery(payload);
if (message === "GET_DEPARTURES"){
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"ET-Client-Name": payload.ETClientName
},
body: JSON.stringify({ query: body }),
};
console.log(fetch); // Check if 'fetch' is available
const res = await fetch(payload.url, options);
console.log("return code: " + res.status);
if (res.status === 200 || res.status === 304) {
const rb = await res.json();
const path = !!rb.data.stopPlace ? rb.data.stopPlace : rb.data.quay;
console.log(rb.data);
this.sendSocketNotification("DEPARTURE_LIST", path);
}
}
} catch (e) {
console.log(e);
// Handle errors as needed
}
}
});