1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! Service layer for user drawings.

use actix_web::web::Data;
use uuid::Uuid;

use crate::config::data::AppDataInner;
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,
    app_data: &Data<AppDataInner>,
) -> Result<Vec<DrawingDto>, ServiceError> {
    let mut conn = app_data.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>,
    app_data: &Data<AppDataInner>,
) -> Result<Vec<DrawingDto>, ServiceError> {
    let mut conn = app_data.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,
    app_data: &Data<AppDataInner>,
) -> Result<Vec<DrawingDto>, ServiceError> {
    let mut conn = app_data.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>,
    app_data: &Data<AppDataInner>,
) -> Result<(), ServiceError> {
    let mut conn = app_data.pool.get().await?;
    let _ = Drawing::delete_by_ids(ids, &mut conn).await?;
    Ok(())
}