2020-02-08 18:59:51 +00:00
|
|
|
const router = require('express').Router();
|
|
|
|
|
|
|
|
const Roads = require('../models/roadsModel');
|
|
|
|
const Cities = require('../models/citiesModel');
|
|
|
|
|
2020-02-09 17:06:33 +00:00
|
|
|
const findShortestPath = require('../../helpers/dijkstra_algo');
|
2020-02-08 18:59:51 +00:00
|
|
|
|
|
|
|
router.get('', async (req, res) => {
|
2020-02-09 16:57:50 +00:00
|
|
|
const { start_city_id, end_city_id } = req.query;
|
|
|
|
|
|
|
|
start = Math.floor(start_city_id);
|
|
|
|
end = Math.floor(end_city_id);
|
2020-02-08 18:59:51 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const cities = await Cities.getCities();
|
|
|
|
const roads = await Roads.getRoads();
|
|
|
|
|
2020-02-09 17:06:33 +00:00
|
|
|
let { path, distance } = findShortestPath(cities, roads, start, end);
|
|
|
|
const shortestPath = formatPath(path, cities)
|
2020-02-08 18:59:51 +00:00
|
|
|
|
2020-02-09 17:06:33 +00:00
|
|
|
let response = { path: shortestPath, distance }
|
2020-02-08 18:59:51 +00:00
|
|
|
|
|
|
|
res.status(200).json(response);
|
|
|
|
} catch (e) {
|
|
|
|
res.status(500).json(e);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
function formatPath(path, cities) {
|
|
|
|
const complete_path = []
|
|
|
|
|
|
|
|
for (let path_city of path) {
|
|
|
|
for (let city of cities) {
|
|
|
|
if (city.id == path_city) {
|
|
|
|
complete_path.push({ id: city.id, name: city.name });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return complete_path
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = router;
|