//! Simplistic model layer //! (with mock-store layer) use crate::{Error, Result, ctx::Ctx}; use serde::{Deserialize, Serialize}; use std::sync::{Arc, Mutex}; // region: --- Property Types #[derive(Clone, Debug, Serialize)] pub struct Property { pub id: u64, pub creator_id: u64, pub address: String, pub contact: String, } #[derive(Deserialize)] pub struct PropertyForCreate { pub address: String, pub contact: String, } // endregion: --- Property Types // region: --- Model Controller #[derive(Clone)] pub struct ModelController { property_store: Arc>>>, } // Constructor impl ModelController { pub async fn new() -> Result { Ok(Self { property_store: Arc::default() }) } } // CRUD implementation impl ModelController { pub async fn create_property(&self, ctx: Ctx, property: PropertyForCreate) -> Result { let mut store = self.property_store.lock().unwrap(); let id = store.len() as u64; let property = Property { id, creator_id: ctx.user_id(), address: property.address, contact: property.contact }; store.push(Some(property.clone())); Ok(property) } pub async fn list_properties(&self, ctx: Ctx) -> Result> { let store = self.property_store.lock().unwrap(); let properties = store.iter().filter_map(|p| p.clone()).collect(); Ok(properties) } pub async fn delete_property(&self, ctx: Ctx, id: u64) -> Result { let mut store = self.property_store.lock().unwrap(); let property = store.get_mut(id as usize).and_then(|p| p.take()); property.ok_or(Error::PropertyDeleteFailIdNotFound { id }) } } // endregion: --- Model Controller