Move db querying logic to separate files

This commit is contained in:
Maciej Pędzich 2024-04-29 21:16:11 +02:00
parent 9d3cd78523
commit 2d2965322f
Signed by: maciejpedzich
GPG Key ID: CE4A303D84882F0D
3 changed files with 80 additions and 0 deletions

16
src/db/getDriverNames.ts Normal file
View File

@ -0,0 +1,16 @@
import { db } from '.';
export async function getDriverNames() {
const { records } = await db.executeQuery(
`MATCH (d:Driver)
RETURN
(d.forename + " " + d.surname) AS fullname
ORDER BY
toUpper(d.surname),
toUpper(d.forename)`
);
const driverNames = records.map((rec) => rec.get('fullname') as string);
return driverNames;
}

View File

@ -0,0 +1,64 @@
import type { Path } from 'neo4j-driver';
import type { Edge, Node } from 'vis-network';
import type { Driver } from '@/models/driver';
import { db } from '.';
export async function getShortestPaths(source: string, dest: string) {
let nodes: Node[] = [];
let edges: Edge[] = [];
let numPaths = 0;
let degsOfSeparation = 0;
const { records } = await db.executeQuery(
`MATCH (n:Driver)
WHERE
(n.forename + " " + n.surname) = $source
OR (n.forename + " " + n.surname) = $dest
WITH collect(n) AS nodes
UNWIND nodes AS s
UNWIND nodes AS d
WITH *
WHERE
(s.forename + " " + s.surname) = $source
AND (d.forename + " " + d.surname) = $dest
MATCH path = allShortestPaths((s)-[*..20]-(d))
RETURN path`,
{ source, dest }
);
numPaths = records.length;
degsOfSeparation =
records.length > 0 ? (records[0].get('path') as Path).length : 0;
const pairsOfRelatedDrivers = records.flatMap((rec) =>
(rec.get('path') as Path).segments.map(
({ start, end }) => [start.properties, end.properties] as Driver[]
)
);
nodes = [
...new Map(
pairsOfRelatedDrivers.flatMap((pair) =>
pair.map(({ driverId, forename, surname }) => [
driverId.toNumber(),
forename + ' ' + surname
])
)
).entries()
].map(([id, label]) => ({ id, label }));
edges = [
...new Set(
pairsOfRelatedDrivers.map(
([from, to]) => from.driverId.toString() + '-' + to.driverId.toString()
)
).values()
].map((pair) => {
const [from, to] = pair.split('-').map(Number);
return { from, to };
});
return { nodes, edges, numPaths, degsOfSeparation };
}