-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtflApiClient.js
More file actions
69 lines (57 loc) · 2.42 KB
/
tflApiClient.js
File metadata and controls
69 lines (57 loc) · 2.42 KB
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
const request = require("request");
const getLiveArrivalPredictions = (userStopCode) => {
return new Promise((resolve, reject) => {
request(`https://api.tfl.gov.uk/StopPoint/${userStopCode}/Arrivals`, function (error, response, body) {
if (response.statusCode === 200 && !error) {
const sortedArrivals = JSON.parse(body).sort((b1, b2) => b1.timeToStation - b2.timeToStation);
resolve(sortedArrivals)
} else {
reject(Error("Unable to fetch data"))
}
})
})
}
const logArrivals = (sortedArrivals) => {
console.log(`Bus stop: ${sortedArrivals[0].stationName}`);
sortedArrivals.map(a => {
if(sortedArrivals.indexOf(a) <= 4) {
let arrivalTime = Math.floor(a.timeToStation/60);
console.log(`${a.lineId} to ${a.destinationName} ${arrivalTime <= 0 ? 'due' : 'arriving in ' + arrivalTime + ' minutes'}`)
}
})
}
const convertArrivalsToArrivalObjects = (arrivals) => {
return arrivals.map((arrival) => {
let busArrival = new Arrival(
arrival.lineId,
Math.floor(arrival.timeToStation/60),
arrival.stationName,
arrival.naptanId,
arrival.destinationName
)
})
}
async function getArrivals(userStopCode) {
const data = await Promise.resolve(getLiveArrivalPredictions(userStopCode));
return data
}
const fetchBusStops = (data) => {
return new Promise((resolve, reject) => {
request(`https://api.tfl.gov.uk/StopPoint?stopTypes=NaptanPublicBusCoachTram&lat=
${data[0]}&lon=${data[1]}&radius=800`, function (error, response, body) {
if (response.statusCode === 200 & !error) {
try {
const busStops = JSON.parse(body);
const closestBusStops = [busStops['stopPoints'][0], busStops['stopPoints'][1]];
resolve(closestBusStops);
} catch {
throw new Error('It looks like there are no bus stops nearby. Please try again')
}
} else {
reject(Error("Unable to complete request"))
}
})
})
}
module.exports = {convertArrivalsToArrivalObjects, fetchBusStops, getLiveArrivalPredictions};
// 490008660N