This repository has been archived by the owner on Jun 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
etafetcher.js
116 lines (99 loc) · 2.74 KB
/
etafetcher.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
/* Magic Mirror
* Node Helper: MMM-HK-Transport - ETAFetcher
*
* By Winston / https://github.com/winstonma
* AGPL-3.0 Licensed.
*/
const Log = require("../../js/logger.js");
const got = require('got');
/**
* Responsible for requesting an update on the set interval and broadcasting the data.
*
* @param {string} url URL of the ETA feed.
* @param {string} stopID stop ID of the stop
* @param {number} reloadInterval Reload interval in milliseconds.
* @class
*/
const ETAFetcher = function (url, stopID, reloadInterval) {
const self = this;
let reloadTimer = null;
let item = null;
let fetchFailedCallback = function () { };
let itemsReceivedCallback = function () { };
if (reloadInterval < 1000) {
reloadInterval = 1000;
}
/* private methods */
/**
* Request the ETA
*/
const fetchETAs = function () {
clearTimeout(reloadTimer);
reloadTimer = null;
item = [];
(async () => {
try {
const {body} = await got(url, {
responseType: 'json'
});
item = body;
self.broadcastItems();
scheduleTimer();
} catch (error) {
console.log(error.response.body);
fetchFailedCallback(self, error);
scheduleTimer();
}
})();
};
/**
* Schedule the timer for the next update.
*/
const scheduleTimer = function () {
clearTimeout(reloadTimer);
reloadTimer = setTimeout(function () {
fetchETAs();
}, reloadInterval);
};
/* public methods */
/**
* Update the reload interval, but only if we need to increase the speed.
*
* @param {number} interval Interval for the update in milliseconds.
*/
this.setReloadInterval = function (interval) {
if (interval > 1000 && interval < reloadInterval) {
reloadInterval = interval;
}
};
/**
* Initiate fetchETAs();
*/
this.startFetch = function () {
fetchETAs();
};
/**
* Broadcast the existing item.
*/
this.broadcastItems = function () {
if (item.length <= 0) {
Log.info("ETA-Fetcher: No item to broadcast yet.");
return;
}
Log.info(`ETA-Fetcher: Broadcasting item for stop ID ${stopID}`);
itemsReceivedCallback(self);
};
this.onReceive = function (callback) {
itemsReceivedCallback = callback;
};
this.onError = function (callback) {
fetchFailedCallback = callback;
};
this.url = function () {
return url;
};
this.items = function () {
return item;
};
};
module.exports = ETAFetcher;