You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.4 KiB
80 lines
2.4 KiB
use crate::simple::database::PgSharedPool;
|
|
use std::convert::TryInto;
|
|
|
|
use crate::app::forms::GetRobot;
|
|
use crate::base::robots;
|
|
use crate::data::robots::postgres;
|
|
|
|
use crate::simple::HandlingError;
|
|
|
|
pub async fn add_robot(
|
|
shared: std::sync::Arc<std::boxed::Box<crate::simple::shared::SharedContainer>>,
|
|
r: GetRobot,
|
|
) -> Result<GetRobot, HandlingError> {
|
|
let pool = shared.find::<PgSharedPool>().unwrap();
|
|
let mut tx = pool.begin().await?;
|
|
|
|
let model = robots::Robot::new(0, r.name).try_into()?;
|
|
let id = postgres::add(tx.as_mut(), model).await?;
|
|
let robot = postgres::get_by_id(tx.as_mut(), id).await?;
|
|
|
|
tx.commit().await.map_err(|e| HandlingError::DBError(e))?;
|
|
|
|
Ok(robot.into())
|
|
}
|
|
|
|
pub async fn get_robot(
|
|
shared: std::sync::Arc<std::boxed::Box<crate::simple::shared::SharedContainer>>,
|
|
id: i64,
|
|
) -> Result<GetRobot, HandlingError> {
|
|
let pool = shared.find::<PgSharedPool>().unwrap();
|
|
let mut tx = pool.begin().await?;
|
|
Ok(postgres::get_by_id(tx.as_mut(), id).await?.into())
|
|
}
|
|
|
|
pub async fn get_all(
|
|
shared: std::sync::Arc<std::boxed::Box<crate::simple::shared::SharedContainer>>,
|
|
offset: i64,
|
|
limit: i64,
|
|
) -> Result<(Vec<GetRobot>, bool), HandlingError> {
|
|
let pool = shared.find::<PgSharedPool>().unwrap();
|
|
let mut tx = pool.begin().await?;
|
|
|
|
let all = postgres::Collection::new(&mut tx);
|
|
let (items, next) = all.paginate(offset, limit).await?;
|
|
|
|
let data = items.into_iter().map(|r| r.into()).collect();
|
|
|
|
Ok((data, next))
|
|
}
|
|
|
|
pub async fn update_robot(
|
|
shared: std::sync::Arc<std::boxed::Box<crate::simple::shared::SharedContainer>>,
|
|
id: i64,
|
|
r: GetRobot,
|
|
) -> Result<GetRobot, HandlingError> {
|
|
let pool = shared.find::<PgSharedPool>().unwrap();
|
|
let mut tx = pool.begin().await?;
|
|
|
|
let model = robots::Robot::new(id, r.name).try_into()?;
|
|
postgres::update(tx.as_mut(), model).await?;
|
|
let robot = postgres::get_by_id(tx.as_mut(), id).await?;
|
|
|
|
tx.commit().await.map_err(HandlingError::DBError)?;
|
|
|
|
Ok(robot.into())
|
|
}
|
|
|
|
pub async fn delete_robot(
|
|
shared: std::sync::Arc<std::boxed::Box<crate::simple::shared::SharedContainer>>,
|
|
id: i64,
|
|
) -> Result<(), HandlingError> {
|
|
let pool = shared.find::<PgSharedPool>().unwrap();
|
|
let mut tx = pool.begin().await?;
|
|
|
|
postgres::delete(tx.as_mut(), id).await?;
|
|
tx.commit().await.map_err(HandlingError::DBError)?;
|
|
|
|
Ok(())
|
|
}
|