Fix nearby stop grouping and location fallback
This commit is contained in:
17
server.mjs
17
server.mjs
@@ -44,9 +44,9 @@ createServer(async (request, response) => {
|
||||
})
|
||||
|
||||
async function handleDepartures(url, response) {
|
||||
const stopId = url.searchParams.get('stopId') ?? ''
|
||||
const stopCode = url.searchParams.get('stopCode') ?? ''
|
||||
if (!stopId && !stopCode) {
|
||||
const stopIds = uniqueQueryValues(url.searchParams, 'stopId')
|
||||
const stopCodes = uniqueQueryValues(url.searchParams, 'stopCode')
|
||||
if (!stopIds.length && !stopCodes.length) {
|
||||
sendJson(response, 400, { departures: [], error: 'stopId or stopCode is required' })
|
||||
return
|
||||
}
|
||||
@@ -59,7 +59,7 @@ async function handleDepartures(url, response) {
|
||||
|
||||
const feed = await getTripUpdateFeed(apiKey)
|
||||
sendJson(response, 200, {
|
||||
departures: parseTripUpdates(feed, stopId, stopCode),
|
||||
departures: parseTripUpdates(feed, stopIds, stopCodes),
|
||||
updatedAt: Date.now(),
|
||||
})
|
||||
}
|
||||
@@ -85,9 +85,10 @@ async function getTripUpdateFeed(apiKey) {
|
||||
return payload
|
||||
}
|
||||
|
||||
function parseTripUpdates(payload, stopId, stopCode) {
|
||||
function parseTripUpdates(payload, stopIds, stopCodes) {
|
||||
const entities = Array.isArray(payload?.entity) ? payload.entity : []
|
||||
const departures = []
|
||||
const stopIdSet = new Set([...stopIds, ...stopCodes])
|
||||
|
||||
for (const entity of entities) {
|
||||
const tripUpdate = entity.tripUpdate || entity.trip_update || {}
|
||||
@@ -98,7 +99,7 @@ function parseTripUpdates(payload, stopId, stopCode) {
|
||||
|
||||
for (const update of updates) {
|
||||
const updateStopId = update.stopId || update.stop_id
|
||||
if (updateStopId !== stopId && updateStopId !== stopCode) {
|
||||
if (!stopIdSet.has(updateStopId)) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -131,6 +132,10 @@ function parseTripUpdates(payload, stopId, stopCode) {
|
||||
return departures.sort((a, b) => a.dueMinutes - b.dueMinutes).slice(0, 40)
|
||||
}
|
||||
|
||||
function uniqueQueryValues(params, key) {
|
||||
return [...new Set(params.getAll(key).flatMap((value) => value.split(',')).map((value) => value.trim()).filter(Boolean))]
|
||||
}
|
||||
|
||||
async function serveStatic(pathname, response) {
|
||||
const cleanPath = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '')
|
||||
let filePath = join(root, cleanPath === '/' ? 'index.html' : cleanPath)
|
||||
|
||||
Reference in New Issue
Block a user