-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathgasbuddy.js
199 lines (172 loc) · 5.17 KB
/
gasbuddy.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/**
* @file apis/gasbuddy.js
*
* @author fewieden
* @license MIT
*
* @see https://github.com/fewieden/MMM-Fuel
*/
/**
* @external lodash
* @see https://www.npmjs.com/package/lodash
*/
const _ = require('lodash');
/**
* @external node-fetch
* @see https://www.npmjs.com/package/node-fetch
*/
const fetch = require('node-fetch');
/**
* @external node-html-parser
* @see https://www.npmjs.com/package/node-html-parser
*/
const { parse } = require('node-html-parser');
/**
* @external logger
* @see https://github.com/MichMich/MagicMirror/blob/master/js/logger.js
*/
const Log = require('logger');
const { fillMissingPrices, mergePrices, sortByPrice } = require('./utils');
const BASE_URL = 'https://www.gasbuddy.com';
const TYPES = {
regular: 1,
midgrade: 2,
premium: 3,
diesel: 4,
e85: 5,
unl88: 12
};
let config;
/**
* @function getRequestPath
*
* @description URL path for fuel type to request data.
*
* @param {string} type - Fuel type.
*
* @returns {string} URL path for fuel type.
*/
function getRequestPath(type) {
return `/home?search=${config.zip}&fuel=${TYPES[type]}&maxAge=0&method=all`;
}
/**
* @function mapGasStation
* @description Maps HTML gas station to reguilar object.
*
* @param {Object} htmlGasStation - HTML node of gas station.
* @param {string} type - Fuel type.
*
* @returns {Object} Gas station
*/
function mapGasStation(htmlGasStation, type) {
return {
name: htmlGasStation.querySelector('[class*=header__header3___] a[href*=station]').text,
address: htmlGasStation.querySelector('[class*=StationDisplay-module__address___]').innerHTML.replace('<br>', ' '),
prices: { [type]: parseFloat(htmlGasStation.querySelector('[class*=StationDisplayPrice-module__price___]').text.replace('$', '')) },
distance: 0,
stationId: htmlGasStation.querySelector('[class*=header__header3___] a[href*=station]').rawAttributes.href.replace('/station/', '')
};
}
/**
* @function fetchStations
* @description API requests for specified type.
* @async
*
* @param {string} type - Fuel type.
* @param {string} path - URL path.
*
* @returns {Promise} Array with stations including fuelType.
*/
async function fetchStations(type, path) {
let stations = [];
try {
const response = await fetch(`${BASE_URL}${path}`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
}
});
const html = await response.text();
const parsedHtml = parse(html);
const htmlStations = parsedHtml.querySelectorAll('[class*=GenericStationListItem-module__stationListItem___]');
const parsedStations = htmlStations.map(station => mapGasStation(station, type));
stations = stations.concat(parsedStations);
} catch (error) {
Log.error(`MMM-Fuel: Failed to fetch stations for type ${type}`, error);
}
stations.forEach(station => {
station.fuelType = type;
});
return stations;
}
/**
* @function getAllStations
* @description Requests all stations and fuel types.
* @async
*
* @returns {Object[]} Returns object described in the provider documentation.
*/
async function getAllStations() {
const promises = config.types.reduce((acc, type) => {
const path = getRequestPath(type);
acc.push(fetchStations(type, path));
return acc;
}, []);
const responses = await Promise.all(promises);
return responses.flat();
}
/**
* @function getStationKey
* @description Helper to retrieve unique station key.
*
* @param {Object} station - Station
*
* @returns {string} Returns unique station key.
*
* @see apis/README.md
*/
function getStationKey(station) {
return station.stationId;
}
/**
* @function getData
* @description Performs the data query and processing.
* @async
*
* @returns {Object} Returns object described in the provider documentation.
*
* @see apis/README.md
*/
async function getData() {
const responses = await getAllStations();
const { stations, maxPricesByType } = mergePrices(responses, getStationKey);
stations.forEach(station => fillMissingPrices(config, station, maxPricesByType));
// Webpage doesn't support distance (only zip code).
const stationsSortedByPrice = _.sortBy(stations, sortByPrice.bind(null, config));
const stationsSortedByDistance = stationsSortedByPrice;
return {
types: ['regular', 'midgrade', 'premium', 'diesel', 'e85', 'unl88'],
unit: 'mile',
currency: 'USD',
byPrice: stationsSortedByPrice,
byDistance: stationsSortedByDistance
};
}
/**
* @module apis/gasbuddy
* @description Queries data from https://www.gasbuddy.com
*
* @requires external:node-fetch
* @requires external:node-html-parser
* @requires external:logger
*
* @param {Object} options - Configuration.
* @param {string} options.zip - Zip code of address.
* @param {string} options.sortBy - Type to sort by price.
* @param {string[]} options.types - Requested fuel types.
*
* @returns {Object} Object with function getData.
*/
module.exports = options => {
config = options;
return { getData };
};