Files
Project/tools/gtfsRedis.js
2025-12-04 15:37:56 -07:00

100 lines
2.7 KiB
JavaScript

const gtfs = require("./gtfsData");
const redis = require("./redisDAL");
const CACHE_PREFIX = "gtfs_cache";
const RT_TTL = 3;
const STATIC_TTL = 24 * 3600;
async function getCached(keySuffix, fetchFn, ttl) {
await redis.connect();
const cached = await redis.get(CACHE_PREFIX, { key: keySuffix });
if (cached !== null) return cached;
const data = await fetchFn();
await redis.set(CACHE_PREFIX, { key: keySuffix }, data, ttl);
return data;
}
async function getTrains() {
return getCached("trains", gtfs.getTrains, RT_TTL);
}
async function getBuses() {
return getCached("buses", gtfs.getBuses, RT_TTL);
}
async function getTrainsByRoute(route) {
return getCached(`trains_route_${route}`, () => gtfs.getTrainsByRoute(route), RT_TTL);
}
async function getBusesByRoute(route) {
return getCached(`buses_route_${route}`, () => gtfs.getBusesByRoute(route), RT_TTL);
}
async function getAlerts() {
return getCached("alerts", gtfs.getAlerts, RT_TTL);
}
async function getAlertsByRoute(route) {
return getCached(`alerts_route_${route}`, () => gtfs.getAlertsByRoute(route), RT_TTL);
}
async function getScheduleByRoute(route) {
return getCached(`schedule_route_${route}`, () => gtfs.getScheduleByRoute(route), RT_TTL);
}
async function getScheduleByStationId(stopId) {
return getCached(`schedule_stop_${stopId}`, () => gtfs.getScheduleByStationId(stopId), RT_TTL);
}
async function getRoutes() {
return getCached("routes", gtfs.getRoutes, STATIC_TTL);
}
async function getStops() {
return getCached("stops", gtfs.getStops, STATIC_TTL);
}
async function getStopsByRoute(route) {
return getCached(`stops_route_${route}`, () => gtfs.getStopsByRoute(route), STATIC_TTL);
}
async function getShapeByRoute(route) {
return getCached(`shape_route_${route}`, () => gtfs.getShapeByRoute(route), STATIC_TTL);
}
async function updateGtfsRt() {
const data = await gtfs.updateGtfsRt();
await redis.set(CACHE_PREFIX, { key: "trains" }, await gtfs.getTrains(), RT_TTL);
await redis.set(CACHE_PREFIX, { key: "buses" }, await gtfs.getBuses(), RT_TTL);
await redis.set(CACHE_PREFIX, { key: "alerts" }, await gtfs.getAlerts(), RT_TTL);
return data;
}
async function loadGtfsStaticInMemory() {
const data = await gtfs.loadGtfsStaticInMemory();
await redis.set(CACHE_PREFIX, { key: "routes" }, data.routes || [], STATIC_TTL);
await redis.set(CACHE_PREFIX, { key: "stops" }, data.stops || [], STATIC_TTL);
return data;
}
const { gtfs_rt_v, gtfs_rt_t, gtfs_rt_a } = gtfs;
module.exports = {
getStops,
getStopsByRoute,
getRoutes,
getTrains,
getBuses,
getTrainsByRoute,
getBusesByRoute,
getAlerts,
getAlertsByRoute,
getScheduleByRoute,
getScheduleByStationId,
getShapeByRoute,
updateGtfsRt,
loadGtfsStaticInMemory,
};