Add routes for find station by nearest

Signed-off-by: Fred Boniface <fred@fjla.uk>
This commit is contained in:
Fred Boniface 2024-06-30 21:01:06 +01:00
parent e1fc4b1db2
commit 2a9050940d
4 changed files with 43 additions and 3 deletions

View File

@ -1,6 +1,7 @@
const ldb = require("../services/ldb.services");
import { setCache } from "../utils/cacheHeader.utils";
import { logger } from "../utils/logger.utils";
async function getTrain(req, res, next) {
// API v2 Only
@ -65,7 +66,33 @@ async function getStation(req, res, next) {
}
}
async function getNearest(req, res, next) {
// API v2 Only
let latitude = req.params.latitude;
let longitude = req.params.longitude;
try {
if (!req.isAuthed) {
const err = new Error("Unauthorized");
err.status = 401;
return next(err)
}
const data = await ldb.getNearestStations(latitude, longitude)
if (data) {
setCache(res, "private", 120)
} else {
setCache(res, "no-store", 120)
}
res.json(data)
} catch (err) {
setCache(res, "no-store")
logger.Error("Error fetching nearest station")
err.status = 500;
next(err)
}
}
module.exports = {
getTrain,
getStation,
getNearest,
};

View File

@ -4,6 +4,7 @@ const ldbCtr = require("../controllers/ldb.controllers");
// PIS
router.get("/station/:id/:type", ldbCtr.getStation);
router.get("/station/nearest/:latitude/:longitude", ldbCtr.getNearest);
router.get("/train/:searchType/:id", ldbCtr.getTrain);
module.exports = router;

View File

@ -5,6 +5,7 @@ const util = require("../utils/ldb.utils");
const san = require("../utils/sanitizer.utils");
const db = require("../services/dbAccess.services");
import { findStationsByDistancePipeline } from "../utils/ldbPipeline.utils";
import { logger } from "../utils/logger.utils";
import { transform as staffStationTransform } from "../utils/processors/ldb/staffStation";
@ -32,7 +33,7 @@ async function get(id, staff = false) {
logger.error(err, "ldbService.get: Error, Unable to find CRS");
return {
obStatus: "LOC_NOT_FOUND",
obMsg: "UNABLE TO FIND MESSAGE",
obMsg: "Location is not available",
};
}
}
@ -177,6 +178,16 @@ async function getReasonCode(code) {
}
}
async function getNearestStations(lat, long) {
logger.debug(`ldbService.getNearestStations: Fetching nearest stations`)
let pipeline = findStationsByDistancePipeline(4, lat, long)
try {
return await db.queryAggregate(pipeline)
} catch (err) {
logger.error(err, `ldbService.getNearestStations`)
}
}
async function getDateTimeString(date) {
const year = date.getFullYear(),
month = String(date.getMonth() + 1).padStart(2, "0"),
@ -202,4 +213,5 @@ module.exports = {
getServicesByOther,
getReasonCodeList,
getReasonCode,
getNearestStations,
};

View File

@ -1,11 +1,11 @@
export function findStationsByDistancePipeline(count: number) {
export function findStationsByDistancePipeline(count: number, latitude: number, longitude: number) {
return [
{
'$geoNear': {
'near': {
'type': 'Point',
'coordinates': [
-5.149929, 58.350661
longitude, latitude
]
},
'distanceField': 'distance'