zero2prod_axum/src/model.rs
2023-10-15 22:30:01 +02:00

62 lines
1.7 KiB
Rust

//! 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<Mutex<Vec<Option<Property>>>>,
}
// Constructor
impl ModelController {
pub async fn new() -> Result<Self> {
Ok(Self { property_store: Arc::default() })
}
}
// CRUD implementation
impl ModelController {
pub async fn create_property(&self, ctx: Ctx, property: PropertyForCreate) -> Result<Property> {
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<Vec<Property>> {
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<Property> {
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