Add AppState to Controller and split up models
This commit is contained in:
parent
8dc9072fe8
commit
83c1f033d5
11 changed files with 261 additions and 150 deletions
emgauwa-lib/src/models
70
emgauwa-lib/src/models/relay.rs
Normal file
70
emgauwa-lib/src/models/relay.rs
Normal file
|
@ -0,0 +1,70 @@
|
|||
use futures::executor::block_on;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use sqlx::pool::PoolConnection;
|
||||
use sqlx::Sqlite;
|
||||
|
||||
use crate::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
|
||||
use crate::errors::DatabaseError;
|
||||
use crate::models::FromDbModel;
|
||||
use crate::types::{ControllerUid, Weekday};
|
||||
use crate::utils;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Relay {
|
||||
#[serde(flatten)]
|
||||
pub r: DbRelay,
|
||||
pub controller: DbController,
|
||||
pub controller_id: ControllerUid,
|
||||
pub schedules: Vec<DbSchedule>,
|
||||
pub active_schedule: DbSchedule,
|
||||
pub tags: Vec<String>,
|
||||
}
|
||||
|
||||
|
||||
impl FromDbModel for Relay {
|
||||
type DbModel = DbRelay;
|
||||
type DbModelCache = DbController;
|
||||
|
||||
fn from_db_model(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
db_model: Self::DbModel,
|
||||
) -> Result<Self, DatabaseError> {
|
||||
let cache = block_on(db_model.get_controller(conn))?;
|
||||
Self::from_db_model_cache(conn, db_model, cache)
|
||||
}
|
||||
|
||||
fn from_db_model_cache(
|
||||
conn: &mut PoolConnection<Sqlite>,
|
||||
db_model: Self::DbModel,
|
||||
cache: Self::DbModelCache,
|
||||
) -> Result<Self, DatabaseError> {
|
||||
let tags = block_on(db_model.get_tags(conn))?;
|
||||
let controller_id = cache.uid.clone();
|
||||
|
||||
let schedules = block_on(DbJunctionRelaySchedule::get_schedules(conn, &db_model))?;
|
||||
|
||||
let weekday = utils::get_weekday();
|
||||
let active_schedule = block_on(DbJunctionRelaySchedule::get_schedule(
|
||||
conn,
|
||||
&db_model,
|
||||
weekday as Weekday,
|
||||
))?
|
||||
.ok_or(DatabaseError::NotFound)?;
|
||||
|
||||
Ok(Relay {
|
||||
r: db_model,
|
||||
controller: cache,
|
||||
controller_id,
|
||||
schedules,
|
||||
active_schedule,
|
||||
tags,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Relay {
|
||||
pub fn reload(&mut self, conn: &mut PoolConnection<Sqlite>) -> Result<(), DatabaseError> {
|
||||
self.r = block_on(self.r.reload(conn))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue