cdb/src/location.rs

79 lines
1.9 KiB
Rust
Raw Normal View History

2024-09-18 08:29:27 +02:00
use std::{future::Future, pin::Pin};
use futures::FutureExt;
2024-09-02 18:40:02 +02:00
use mongod::{
derive::{Model, Referencable},
Model, ToAPI, Validate,
};
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use serde_json::json;
/// A Storage Location
#[derive(Debug, Clone, Serialize, Deserialize, Model, Referencable)]
pub struct Location {
/// UUID
2024-09-02 19:10:22 +02:00
#[serde(default)]
2024-09-02 18:40:02 +02:00
pub _id: String,
/// Name
pub name: String,
/// Parent
pub parent: Option<String>,
/// Storage Conditions
pub conditions: Option<StorageConditions>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StorageConditions {
/// Median temperature
pub temperature: i64,
}
impl Validate for Location {
async fn validate(&self) -> Result<(), String> {
Ok(())
}
}
2024-09-18 08:29:27 +02:00
impl Location {
/// Recursively get the conditions of a location. This inherits from parent locations.
pub fn conditions_rec<'a>(
&'a self,
) -> futures::future::BoxFuture<'a, Option<StorageConditions>> {
async move {
if let Some(cond) = &self.conditions {
return Some(cond.clone());
}
if let Some(parent) = &self.parent {
if let Some(parent_loc) = Location::get(parent).await {
if let Some(cond) = parent_loc.conditions_rec().await {
return Some(cond);
}
}
}
None
}
.boxed()
}
}
2024-09-02 18:40:02 +02:00
impl ToAPI for Location {
async fn api(&self) -> serde_json::Value {
json!({
2024-09-12 10:17:14 +02:00
"id": self._id,
2024-09-02 18:40:02 +02:00
"name": self.name,
"parent": self.parent,
2024-09-18 08:29:27 +02:00
"conditions": self.conditions_rec().await
2024-09-02 18:40:02 +02:00
})
}
}
impl Location {
2024-09-02 19:10:22 +02:00
pub async fn add(&mut self, id: &str) {
self._id = id.to_string();
self.insert_overwrite().await.unwrap();
2024-09-02 18:40:02 +02:00
}
}