Improve controller endpoint and model
This commit is contained in:
parent
2f51ebf91e
commit
6400b7745c
5 changed files with 103 additions and 7 deletions
emgauwa-lib/src
|
@ -4,8 +4,9 @@ use sqlx::pool::PoolConnection;
|
|||
use sqlx::Sqlite;
|
||||
|
||||
use crate::db::errors::DatabaseError;
|
||||
use crate::db::{DbController, DbRelay, DbSchedule};
|
||||
use crate::types::ControllerUid;
|
||||
use crate::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
|
||||
use crate::types::{ControllerUid, Weekday};
|
||||
use crate::utils;
|
||||
|
||||
pub trait FromDbModel {
|
||||
type DbModel: Clone;
|
||||
|
@ -40,6 +41,8 @@ pub struct Relay {
|
|||
pub r: DbRelay,
|
||||
pub controller: DbController,
|
||||
pub controller_id: ControllerUid,
|
||||
pub schedules: Vec<DbSchedule>,
|
||||
pub active_schedule: DbSchedule,
|
||||
pub tags: Vec<String>,
|
||||
}
|
||||
|
||||
|
@ -96,10 +99,23 @@ impl FromDbModel for Relay {
|
|||
let tags = executor::block_on(db_model.get_tags(conn))?;
|
||||
let controller_id = cache.uid.clone();
|
||||
|
||||
let schedules =
|
||||
executor::block_on(DbJunctionRelaySchedule::get_schedules(conn, &db_model))?;
|
||||
|
||||
let weekday = utils::get_weekday();
|
||||
let active_schedule = executor::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,
|
||||
})
|
||||
}
|
||||
|
|
|
@ -67,9 +67,12 @@ impl<'r> Decode<'r, Sqlite> for ControllerUid {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<&str> for ControllerUid {
|
||||
fn from(value: &str) -> Self {
|
||||
Self(Uuid::from_str(value).unwrap())
|
||||
impl TryFrom<&str> for ControllerUid {
|
||||
type Error = uuid::Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
let uuid = Uuid::from_str(value)?;
|
||||
Ok(Self(uuid))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,8 +1,11 @@
|
|||
use std::str::FromStr;
|
||||
|
||||
use chrono::Datelike;
|
||||
use log::LevelFilter;
|
||||
use simple_logger::SimpleLogger;
|
||||
|
||||
use crate::types::Weekday;
|
||||
|
||||
pub fn load_settings<T>(config_name: &str, env_prefix: &str) -> T
|
||||
where
|
||||
for<'de> T: serde::Deserialize<'de>,
|
||||
|
@ -31,3 +34,11 @@ pub fn init_logging(level: &str) {
|
|||
.init()
|
||||
.expect("Error initializing logger.");
|
||||
}
|
||||
|
||||
pub fn get_weekday() -> Weekday {
|
||||
(chrono::offset::Local::now()
|
||||
.date_naive()
|
||||
.weekday()
|
||||
.number_from_monday()
|
||||
- 1) as Weekday
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue