//! Service layer for user drawings.
use uuid::Uuid;
use crate::config::data::SharedPool;
use crate::error::ServiceError;
use crate::model::dto::drawings::{DrawingDto, UpdateDrawingsDto};
use crate::model::entity::drawings::Drawing;
/// Get all drawings from one map.
///
/// # Errors
/// If the connection to the database could not be established.
pub async fn find(map_id: i32, pool: &SharedPool) -> Result<Vec<DrawingDto>, ServiceError> {
let mut conn = pool.get().await?;
let results = Drawing::find(map_id, &mut conn).await?;
results.into_iter().map(TryFrom::try_from).collect()
}
/// Save new drawing.
///
/// # Errors
/// If the connection to the database could not be established.
pub async fn create(
dtos: Vec<DrawingDto>,
pool: &SharedPool,
) -> Result<Vec<DrawingDto>, ServiceError> {
let mut conn = pool.get().await?;
let drawing_updates = dtos
.into_iter()
.map(Drawing::try_from)
.collect::<Result<Vec<Drawing>, ServiceError>>()?;
let result = Drawing::create(drawing_updates, &mut conn).await?;
result.into_iter().map(TryFrom::try_from).collect()
}
/// Update the drawing in the database.
///
/// # Errors
/// If the connection to the database could not be established.
pub async fn update(
dto: UpdateDrawingsDto,
pool: &SharedPool,
) -> Result<Vec<DrawingDto>, ServiceError> {
let mut conn = pool.get().await?;
let result = Drawing::update(dto.try_into()?, &mut conn).await?;
result.into_iter().map(TryFrom::try_from).collect()
}
/// Delete drawings from the databse.
///
/// # Errors
/// If the connection to the database could not be established.
pub async fn delete_by_ids(ids: Vec<Uuid>, pool: &SharedPool) -> Result<(), ServiceError> {
let mut conn = pool.get().await?;
let _ = Drawing::delete_by_ids(ids, &mut conn).await?;
Ok(())
}