2024-05-29 13:40:37 +02:00
|
|
|
use crate::backend::types::{City, Road, ShortestPath};
|
|
|
|
use crate::graph::graph::{all_cities, create_city, create_road, shortest_path};
|
|
|
|
use neo4rs::{Graph};
|
|
|
|
use rocket::response::status::{BadRequest};
|
2024-05-24 13:09:17 +02:00
|
|
|
use rocket::serde::json::Json;
|
2024-05-29 13:40:37 +02:00
|
|
|
use rocket::{get, post, Route, State};
|
|
|
|
use rocket_okapi::{openapi, openapi_get_routes};
|
2024-05-24 13:09:17 +02:00
|
|
|
|
2024-05-29 13:40:37 +02:00
|
|
|
/// configure available api nodes
|
2024-05-24 13:09:17 +02:00
|
|
|
pub fn build_api() -> Vec<Route> {
|
2024-05-29 13:40:37 +02:00
|
|
|
openapi_get_routes![addcity, addroad, getshortestpath, getallcities]
|
|
|
|
}
|
|
|
|
|
|
|
|
/// endpoint to add new city to graph
|
|
|
|
#[openapi]
|
|
|
|
#[post("/addcity", data = "<msg>")]
|
|
|
|
pub async fn addcity(graph: &State<Graph>, msg: Json<City>) -> Result<String, BadRequest<String>> {
|
|
|
|
match create_city(graph, msg.into_inner()).await {
|
|
|
|
Ok(_) => Ok("ok".to_string()),
|
|
|
|
Err(e) => Err(BadRequest(e.to_string())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// endpoint to add new road between two cities
|
|
|
|
#[openapi]
|
|
|
|
#[post("/road", data = "<msg>")]
|
|
|
|
pub async fn addroad(graph: &State<Graph>, msg: Json<Road>) -> Result<String, BadRequest<String>> {
|
|
|
|
match create_road(graph, msg.into_inner()).await {
|
|
|
|
Ok(_) => Ok("ok".to_string()),
|
|
|
|
Err(e) => Err(BadRequest(e.to_string())),
|
|
|
|
}
|
2024-05-24 13:09:17 +02:00
|
|
|
}
|
|
|
|
|
2024-05-29 13:40:37 +02:00
|
|
|
/// endpoint to get all available cities with optional limit
|
|
|
|
#[openapi]
|
|
|
|
#[get("/cities?<limit>")]
|
|
|
|
pub async fn getallcities(graph: &State<Graph>, limit: Option<i32>) -> Result<Json<Vec<String>>, BadRequest<String>> {
|
|
|
|
match all_cities(graph, limit).await {
|
|
|
|
Ok(v) => Ok(Json::from(v)),
|
|
|
|
Err(e) => Err(BadRequest(e.to_string())),
|
|
|
|
}
|
|
|
|
}
|
2024-05-24 13:09:17 +02:00
|
|
|
|
2024-05-29 13:40:37 +02:00
|
|
|
/// endpoint to get shortest path between two cities with the resulting length
|
|
|
|
#[openapi]
|
|
|
|
#[get("/shortestpath?<city1>&<city2>")]
|
|
|
|
pub async fn getshortestpath(
|
|
|
|
graph: &State<Graph>,
|
|
|
|
city1: String,
|
|
|
|
city2: String,
|
|
|
|
) -> Result<Json<ShortestPath>, BadRequest<String>> {
|
|
|
|
match shortest_path(graph, city1, city2).await {
|
|
|
|
Ok(v) => Ok(Json::from(v)),
|
|
|
|
Err(e) => Err(BadRequest(e.to_string())),
|
|
|
|
}
|
2024-05-24 13:09:17 +02:00
|
|
|
}
|