Merge pull request #1 from ruihildt/completed-backend

Completed backend with documentation
This commit is contained in:
rui 2020-02-10 03:30:46 +01:00 committed by GitHub
commit aa2f6838fa
18 changed files with 1319 additions and 17 deletions

136
README.md Normal file
View File

@ -0,0 +1,136 @@
# dijkstra-backend
Dijkstra is an app thas uses Dijkstra algorithm to display the shortest path between different cities in Belgium.
Deployed backend: https://dijkstra-backend.herokuapp.com/
## API Documentation
___
> Values required in **`bold`**.
### COUNTRIES **`countries`**
| field | data type | metadata |
| :--------| :---------------- | :-------------------------------------------------- |
| id | unsigned integer | primary key, auto-increments, generated by database |
| name | string | |
#### Get countries list
**`GET /api/countries/:country_id`**
##### Response
An array of json objects with a list of cities in the selected country with `name`, `id` and `country_id`.
```
[
{
"id": 1,
"name": "bruges",
"country_id": 1
},
{
"id": 2,
"name": "antwerp",
"country_id": 1
},
{
"id": 3,
"name": "ghent",
"country_id": 1
},
]
```
### CITIES **`cities`**
| field | data type | metadata |
| :----------| :--------------------- | :-------------------------------------------------- |
| id | unsigned integer | primary key, auto-increments, generated by database |
| name | string | |
| country_id | unsigned integer | foreign key referencing `countries.id` |
#### Get cities list
**`GET /api/cities`**
##### Response
An array of json objects with `id`, `name` and `country_id`.
```
[
{
"id": 1,
"name": 'bruges',
"country_id": 1
}
]
```
### ROADS **`roads`**
| field | data type | metadata |
| :-------------| :--------------- | :-------------------------------------------------- |
| id | unsigned integer | primary key, auto-increments, generated by database |
| start_city_id | string | required |
| end_city_id | string | required |
| distance | unsigned integer | |
#### Get roads list
**`GET /api/roads`**
##### Response
A array of json objects with `id`, `start_city_id`, 'end_city_id` and `distance`.
```
[
{
"id": 1,
"start_city_id": 1,
"end_city_id": 3,
"distance": 50
}
]
```
### Shortest Path **`cities`**
#### Get the shortest path between two cities and the total distance
**`GET /api/path`**
##### Request
Add the **`start_city_id`** and **`end_city_id`** as query strings to the url.
```
/api/path?start_city_id=2?end_city_id=9
```
##### Response
A json object composed of the `path` correctly ordered and the total `distance`.
```
{
"path": [
{
"id": 2,
"name": "antwerp"
},
{
"id": 4,
"name": "mechelen"
},
{
"id": 5,
"name": "brussels"
},
{
"id": 8,
"name": "liege"
},
{
"id": 7,
"name": "namur"
},
{
"id": 9,
"name": "arlon"
}
],
"distance": 337
}
```

22
api/models/citiesModel.js Normal file
View File

@ -0,0 +1,22 @@
const db = require('../../data/dbConfig');
module.exports = {
getCities,
getCitiesByCountry
// getCity,
};
function getCities() {
return db('cities')
}
function getCitiesByCountry(country_id) {
return db('cities')
.where({ country_id })
}
// function getCity(name) {
// return db('cities')
// .where({ name })
// .first()
// }

View File

@ -1,4 +1,4 @@
const db = require('../data/dbConfig');
const db = require('../../data/dbConfig');
module.exports = {
getCountries,

9
api/models/roadsModel.js Normal file
View File

@ -0,0 +1,9 @@
const db = require('../../data/dbConfig');
module.exports = {
getRoads
};
function getRoads() {
return db('roads')
}

View File

@ -0,0 +1,14 @@
const router = require('express').Router();
const Cities = require('../models/citiesModel');
router.get('', async (req, res) => {
try {
const cities = await Cities.getCities();
res.status(200).json(cities);
} catch (e) {
res.status(500).json(e);
}
})
module.exports = router;

View File

@ -0,0 +1,14 @@
const router = require('express').Router();
const Cities = require('../models/citiesModel');
router.get('/:country_id', async (req, res) => {
const { country_id } = req.params;
try {
const cities = await Cities.getCitiesByCountry(country_id);
res.status(200).json(cities);
} catch (e) {
res.status(500).json(e);
}
})
module.exports = router;

43
api/routes/pathRouter.js Normal file
View File

@ -0,0 +1,43 @@
const router = require('express').Router();
const Roads = require('../models/roadsModel');
const Cities = require('../models/citiesModel');
const findShortestPath = require('../../helpers/dijkstra_algo');
router.get('', async (req, res) => {
const { start_city_id, end_city_id } = req.query;
start = Math.floor(start_city_id);
end = Math.floor(end_city_id);
try {
const cities = await Cities.getCities();
const roads = await Roads.getRoads();
let { path, distance } = findShortestPath(cities, roads, start, end);
const shortestPath = formatPath(path, cities)
let response = { path: shortestPath, distance }
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;

13
api/routes/roadsRouter.js Normal file
View File

@ -0,0 +1,13 @@
const router = require('express').Router();
const Roads = require('../models/roadsModel');
router.get('', async (req, res) => {
try {
const roads = await Roads.getRoads();
res.status(200).json(roads);
} catch (e) {
res.status(500).json(e);
}
})
module.exports = router;

View File

@ -1,17 +1,21 @@
const express = require("express");
const helmet = require('helmet');
const cors = require('cors');
// const authRouter = require('../services/auth/authRouter');
// const usersRouter = require('../services/users/usersRouter');
// const sessionsRouter = require('../services/sessions/sessionsRouter');
// const dailyAveragesRouter = require('../services/dailyAverages/dailyAveragesRouter');
const citiesRouter = require('./routes/citiesRouter');
const roadsRouter = require('./routes/roadsRouter');
const countriesRouter = require('./routes/countriesRouter');
const pathRouter = require('./routes/pathRouter')
const server = express();
server.use(helmet());
server.use(express.json());
server.use(cors());
// server.use('/api/auth', authRouter);
// server.use('/api/users', authenticate, usersRouter);
// server.use('/api/users', authenticate, sessionsRouter);
// server.use('/api/users', authenticate, dailyAveragesRouter);
server.use('/api/cities', citiesRouter);
server.use('/api/roads', roadsRouter);
server.use('/api/countries', countriesRouter);
server.use('/api/path', pathRouter);
module.exports = server;

55
helpers/dijkstra_algo.js Normal file
View File

@ -0,0 +1,55 @@
const Queue = require('./queue');
const Graph = require('./graph');
function findPathWithDijkstra(cities, roads, startNode, endNode) {
const graph = new Graph();
// Add cities and roads to graph
for (let city of cities) {
graph.addNode(city.id)
}
for (let { start_city_id, end_city_id, distance } of roads) {
graph.addEdge(start_city_id, end_city_id, distance)
}
// Dijkstra path search algo
let times = {};
let backtrace = {};
let queue = new Queue();
times[startNode] = 0;
graph.nodes.forEach(node => {
if (node !== startNode) {
times[node] = Infinity
}
});
queue.enqueue([startNode, 0]);
while (queue.size()) {
let shortestStep = queue.dequeue();
let currentNode = shortestStep[0];
graph.adjacencyList[currentNode].forEach(neighbor => {
let time = times[currentNode] + neighbor.distance;
if (time < times[neighbor.node]) {
times[neighbor.node] = time;
backtrace[neighbor.node] = currentNode;
queue.enqueue([neighbor.node, time]);
}
});
}
let path = [endNode];
let lastStep = endNode; while(lastStep !== startNode) {
path.unshift(backtrace[lastStep])
lastStep = backtrace[lastStep]
}
// return `Path is ${path} and time is ${times[endNode]}`
return {path, distance: times[endNode]}
}
module.exports = findPathWithDijkstra;

18
helpers/graph.js Normal file
View File

@ -0,0 +1,18 @@
class Graph {
constructor() {
this.nodes = [];
this.adjacencyList = {};
}
addNode(node) {
this.nodes.push(node);
this.adjacencyList[node] = [];
}
addEdge(node1, node2, distance) {
this.adjacencyList[node1].push({node:node2, distance});
this.adjacencyList[node2].push({node:node1, distance});
}
}
module.exports = Graph;

21
helpers/queue.js Normal file
View File

@ -0,0 +1,21 @@
class Queue {
constructor() {
this.store = [];
}
size() {
return this.store.length
}
enqueue(node) {
this.store.push(node);
}
dequeue() {
if (this.size() > 0) {
return this.store.shift();
}
}
}
module.exports = Queue;

View File

@ -3,7 +3,7 @@ const server = require("./api/server");
server.get("/", (req, res) => {
res.json({
message: `API server for Dijkstra. :)`,
documentation: `Coming`
documentation: `Check out: https://github.com/ruihildt/dijkstra/tree/completed-backend`
});
});

View File

View File

951
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,14 +4,18 @@
"description": "",
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"helmet": "^3.21.2",
"knex": "^0.20.8",
"nodejs": "^0.0.0",
"sqlite3": "^4.1.1"
},
"devDependencies": {},
"devDependencies": {
"nodemon": "^2.0.2"
},
"scripts": {
"test": "test",
"watch": "nodemon index.js",
"start": "node index.js"
},
"author": "",