2023-10-05 14:33:12 +02:00
|
|
|
//! Simplistic model layer
|
|
|
|
|
//! (with mock-store layer)
|
|
|
|
|
|
2023-10-15 22:30:01 +02:00
|
|
|
use crate::{Error, Result, ctx::Ctx};
|
2023-10-05 14:33:12 +02:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
|
|
|
|
|
|
// region: --- Property Types
|
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
|
|
|
pub struct Property {
|
|
|
|
|
pub id: u64,
|
2023-10-15 22:30:01 +02:00
|
|
|
pub creator_id: u64,
|
2023-10-05 14:33:12 +02:00
|
|
|
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<Mutex<Vec<Option<Property>>>>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Constructor
|
|
|
|
|
impl ModelController {
|
|
|
|
|
pub async fn new() -> Result<Self> {
|
|
|
|
|
Ok(Self { property_store: Arc::default() })
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// CRUD implementation
|
|
|
|
|
impl ModelController {
|
2023-10-15 22:30:01 +02:00
|
|
|
pub async fn create_property(&self, ctx: Ctx, property: PropertyForCreate) -> Result<Property> {
|
2023-10-05 14:33:12 +02:00
|
|
|
let mut store = self.property_store.lock().unwrap();
|
|
|
|
|
let id = store.len() as u64;
|
2023-10-15 22:30:01 +02:00
|
|
|
let property = Property { id, creator_id: ctx.user_id(), address: property.address, contact: property.contact };
|
2023-10-05 14:33:12 +02:00
|
|
|
store.push(Some(property.clone()));
|
|
|
|
|
Ok(property)
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-15 22:30:01 +02:00
|
|
|
pub async fn list_properties(&self, ctx: Ctx) -> Result<Vec<Property>> {
|
2023-10-05 14:33:12 +02:00
|
|
|
let store = self.property_store.lock().unwrap();
|
|
|
|
|
let properties = store.iter().filter_map(|p| p.clone()).collect();
|
|
|
|
|
Ok(properties)
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-15 22:30:01 +02:00
|
|
|
pub async fn delete_property(&self, ctx: Ctx, id: u64) -> Result<Property> {
|
2023-10-05 14:33:12 +02:00
|
|
|
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
|