121 lines
2.8 KiB
TypeScript
121 lines
2.8 KiB
TypeScript
// Finds PIS Codes using DB Lookups
|
|
|
|
const db = require("../services/dbAccess.services");
|
|
const clean = require("../utils/sanitizer.utils");
|
|
|
|
import { logger } from "../utils/logger.utils";
|
|
import { queryAggregate } from "./dbAccess.services";
|
|
|
|
const supported = ["GW", "UK"];
|
|
|
|
async function findPisByOrigDest(start: string, end: string) {
|
|
logger.debug(
|
|
`pisServices.findPisByOrigDest: Searching for Orig: ${start}, Dest: ${end}`
|
|
);
|
|
const firstCrs = clean.cleanApiEndpointTxt(start.toLowerCase());
|
|
const lastCrs = clean.cleanApiEndpointTxt(end.toLowerCase());
|
|
const query = {
|
|
stops: {
|
|
$all: [
|
|
{ $elemMatch: { $eq: firstCrs } },
|
|
{ $elemMatch: { $eq: lastCrs } },
|
|
],
|
|
},
|
|
$expr: {
|
|
$and: [
|
|
{ $eq: [{ $arrayElemAt: ["$stops", -1] }, lastCrs] },
|
|
{ $eq: [{ $arrayElemAt: ["$stops", 0] }, firstCrs] },
|
|
],
|
|
},
|
|
};
|
|
const search = await db.query("pis", query);
|
|
// Check for results, if none then try partial match
|
|
return search;
|
|
}
|
|
|
|
async function findPisByCode(code: string) {
|
|
logger.debug(`pisServices.findPisByCode: Searching for PIS code: ${code}`);
|
|
const cleanCode = clean.removeNonNumeric(code);
|
|
const query = {
|
|
code: parseInt(cleanCode),
|
|
};
|
|
const search = db.query("pis", query);
|
|
return await search;
|
|
}
|
|
|
|
async function findByTiplocArray(tiplocArray: string[]) {
|
|
const query = {
|
|
tiplocs: tiplocArray,
|
|
};
|
|
const res = await db.query("pis", query);
|
|
// If res is empty then try to find partial match
|
|
if (res.length) {
|
|
return res;
|
|
} else {
|
|
let partial = await findPartialMatchByTiploc(tiplocArray);
|
|
return partial;
|
|
}
|
|
}
|
|
|
|
async function findPartialMatchByTiploc(tiplocArray: string[]) {
|
|
// Do some magic here, similar to findPisByOrigDest but
|
|
// ensuring that the stops in the array match the last
|
|
// x number of items in the array.
|
|
|
|
const pipeline = [
|
|
{
|
|
$addFields: {
|
|
reversedTiplocs: {
|
|
$reverseArray: "$tiplocs",
|
|
},
|
|
reversedQueryArray: {
|
|
$reverseArray: tiplocArray,
|
|
},
|
|
},
|
|
},
|
|
{
|
|
$match: {
|
|
$expr: {
|
|
$gt: [
|
|
{
|
|
$indexOfArray: [
|
|
"$reversedTiplocs",
|
|
{
|
|
$arrayElemAt: ["$reversedQueryArray", 0],
|
|
}
|
|
],
|
|
},
|
|
-1,
|
|
],
|
|
},
|
|
},
|
|
},
|
|
{
|
|
$project: {
|
|
code: 1,
|
|
skipStops: {
|
|
$subtract: [
|
|
{
|
|
$size: "$tiplocs",
|
|
},
|
|
{
|
|
$size: tiplocArray,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
];
|
|
|
|
const res = await queryAggregate('pis', pipeline)
|
|
console.log(JSON.stringify(res))
|
|
return res
|
|
}
|
|
|
|
module.exports = {
|
|
supported,
|
|
findPisByOrigDest,
|
|
findPisByCode,
|
|
findByTiplocArray,
|
|
};
|