feat: add model

This commit is contained in:
Sandro Eiler 2023-10-05 14:33:12 +02:00
parent c5f6a24b3a
commit 42a75ba800
6 changed files with 117 additions and 1 deletions

61
src/model.rs Normal file
View file

@ -0,0 +1,61 @@
//! Simplistic model layer
//! (with mock-store layer)
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
// region: --- Property Types
#[derive(Clone, Debug, Serialize)]
pub struct Property {
pub 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, property: PropertyForCreate) -> Result<Property> {
let mut store = self.property_store.lock().unwrap();
let id = store.len() as u64;
let property = Property { id, address: property.address, contact: property.contact };
store.push(Some(property.clone()));
Ok(property)
}
pub async fn list_properties(&self) -> 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, 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