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>, r: GetRobot, ) -> Result { let pool = shared.find::().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>, id: i64, ) -> Result { let pool = shared.find::().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>, offset: i64, limit: i64, ) -> Result<(Vec, bool), HandlingError> { let pool = shared.find::().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>, id: i64, r: GetRobot, ) -> Result { let pool = shared.find::().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>, id: i64, ) -> Result<(), HandlingError> { let pool = shared.find::().unwrap(); let mut tx = pool.begin().await?; postgres::delete(tx.as_mut(), id).await?; tx.commit().await.map_err(HandlingError::DBError)?; Ok(()) }