const tam = require('./sources/tam'); const util = require('../util'); /** * Fetch real-time information about courses in the TaM network. * * New data will only be fetched from the TaM server if necessary, otherwise * pulling from the in-memory cache. * * @return Mapping from active course IDs to current information about the * course, including its line number, next stop and next stop estimated * time of arrival (ETA). */ let nextUpdate = null; let currentCourses = null; 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;