tracktracker/back/data/realtime.js

81 lines
2.1 KiB
JavaScript

const tam = require('./sources/tam');
const util = require('../util');
let nextUpdate = null;
let currentCourses = null;
/**
* Fetch real-time information about active courses in the TaM network.
*
* New data will only be fetched from the TaM server once every minute,
* otherwise pulling from the in-memory cache.
*
* The following information is provided for each active course:
*
* - `id`: Unique identifier for the course.
* - `line`: Line number.
* - `nextStop`: Identifier of the next stop of the course.
* - `arrivalTime`: Timestamp at which the vehicle is predicted to arrive
* to the next stop.
* - `finalStop`: The final stop to which the course is headed.
*
* @return Mapping from active course IDs to information about each course.
*/
const getCourses = () => new Promise((res, rej) =>
{
if (nextUpdate !== null && Date.now() < nextUpdate)
{
res(currentCourses);
return;
}
const courses = {};
let lastUpdate = null;
tam.fetchRealtime((err, entry) =>
{
if (err)
{
rej(err);
return;
}
if (!util.isObject(entry))
{
currentCourses = courses;
res(currentCourses);
return;
}
if ('lastUpdate' in entry)
{
lastUpdate = entry.lastUpdate;
nextUpdate = entry.nextUpdate;
return;
}
const {
course: id,
routeShortName: line,
stopId: nextStop,
destArCode: finalStop,
} = entry;
const arrivalTime = lastUpdate + parseInt(entry.delaySec, 10) * 1000;
if (!(id in courses))
{
courses[id] = {id, line, nextStop, arrivalTime, finalStop};
}
else if (arrivalTime < courses[id].arrivalTime)
{
// The stop where the next passing is soonest is assumed
// to be the next stop
courses[id].nextStop = nextStop;
courses[id].arrivalTime = arrivalTime;
}
});
});
exports.getCourses = getCourses;