diff --git a/src/location.rs b/src/location.rs index aca348f..6db7930 100644 --- a/src/location.rs +++ b/src/location.rs @@ -35,7 +35,6 @@ impl Validate for Location { impl ToAPI for Location { async fn api(&self) -> serde_json::Value { json!({ - "id": self._id, "name": self.name, "parent": self.parent, "conditions": self.conditions diff --git a/src/main.rs b/src/main.rs index d7694ee..defc5e1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ use std::ops::Deref; use json_store::JSONStore; use location::Location; -use mongod::Model; + use rocket::routes as route; use rocket::{http::Method, launch}; diff --git a/src/routes/item/location.rs b/src/routes/item/location.rs index 29fc867..cc1a7b3 100644 --- a/src/routes/item/location.rs +++ b/src/routes/item/location.rs @@ -1,3 +1,5 @@ +use std::{collections::HashMap, ops::Deref}; + use mongod::ToAPI; use rocket::{get, State}; @@ -18,9 +20,51 @@ pub async fn location_info( Ok(loc.api().await) } +/// Resolve locations children recursively +async fn location_api_resolve( + id: &str, + location: &Location, + locations: &HashMap, +) -> serde_json::Value { + let mut loc_api = location.api().await; + let mut sub_l = HashMap::new(); + + for sub_loc in locations { + if let Some(parent) = &sub_loc.1.parent { + if parent == id { + sub_l.insert( + sub_loc.0.clone(), + Box::pin(location_api_resolve(&sub_loc.0, &sub_loc.1, locations)).await, + ); + } + } + } + + loc_api + .as_object_mut() + .unwrap() + .insert("sub".to_string(), serde_json::to_value(sub_l).unwrap()); + return loc_api; +} + #[get("/locations")] pub async fn locations_info(locations: &State>) -> FallibleApiResponse { - // todo : recursive location map + let mut root_locations = HashMap::new(); - unimplemented!() + for loc in locations.inner().deref() { + if loc.1.parent.is_none() { + root_locations.insert(loc.0, loc.1); + } + } + + let mut location_api = HashMap::new(); + + for loc in &mut root_locations { + location_api.insert( + loc.0, + location_api_resolve(loc.0, loc.1, locations.inner()).await, + ); + } + + Ok(serde_json::to_value(location_api).unwrap()) }