-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
96 lines (79 loc) · 2.93 KB
/
app.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
const express = require('express')
const axios = require('axios').default;
const app = express()
const port = 3000
const APP_ID = "tfl_key"
const APP_KEY = "c918382153274eef95ca07f91a280c17"
class Bus {
constructor(route, destination, timeToArrival) {
this.route = route
this.destination = destination
this.timeToArrival = timeToArrival
}
}
const sortBusesByTime = (busData) => {
return busData.sort((a, b) => {
return a.timeToStation - b.timeToStation
})
}
const getPostCodeData = (postCode) => {
return axios.get(`https://api.postcodes.io/postcodes/${postCode}`)
.then((response) => {
const buses = getBusStopCodes([response.data.result.latitude, response.data.result.longitude])
return buses
})
.catch((error) => {
console.log(error)
})
}
const sortStopsByDistance = (stops) => {
return stops.sort((a, b) => {
return a.distance - b.distance
})
}
const getBusStopCodes = (latAndLon) => {
const [lat, lon] = latAndLon
return axios.get(`https://api.tfl.gov.uk/Stoppoint?lat=${lat}&lon=${lon}&stoptypes=NaptanBusCoachStation,NaptanPublicBusCoachTram&radius=500`)
.then((response) => {
const stopPoints = response.data.stopPoints
const sortedStops = sortStopsByDistance(stopPoints)
const nearestStops = sortedStops.slice(0, 2)
return Promise.all(nearestStops.map(nearestStop => {
return getNextFiveBuses(nearestStop.naptanId)
.then((buses) => {
console.log(buses)
return { "Name": nearestStop.commonName, "Distance": nearestStop.distance, "Departures": buses }
})
}))
})
.catch((error) => {
console.log(error)
})
}
const getNextFiveBuses = (busStopCodes) => {
return axios.get(`https://api.tfl.gov.uk/StopPoint/${busStopCodes}/Arrivals?app_id=${APP_ID}&app_key=${APP_KEY}`)
.then((response) => {
const sortedData = sortBusesByTime(response.data)
const nextFiveBuses = sortedData.slice(0, 5)
const buses = nextFiveBuses.map((busData) => {
return new Bus(busData.lineName, busData.destinationName, busData.timeToStation)
})
return buses
})
.catch((error) => {
console.log(error)
})
}
app.use(express.static('frontend'));
app.use('/history', express.static('frontend/history.html'))
app.get('/', (req, res) => {
res.send('Hello World 2!')
})
app.get('/departureBoards', async (req, res) => {
let postCode = req.query.postcode
const busDeparturesJson = await getPostCodeData(postCode)
res.send(busDeparturesJson)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})