backend/service/
plants.rs

1//! Service layer for plants.
2
3use crate::{
4    config::data::SharedPool,
5    error::ServiceError,
6    model::{
7        dto::{Page, PageParameters, PlantsSearchParameters, PlantsSummaryDto},
8        entity::Plants,
9    },
10};
11
12/// Search plants from in the database.
13///
14/// # Errors
15/// If the connection to the database could not be established.
16pub async fn find(
17    search_parameters: PlantsSearchParameters,
18    page_parameters: PageParameters,
19    pool: &SharedPool,
20) -> Result<Page<PlantsSummaryDto>, ServiceError> {
21    let mut conn = pool.get().await?;
22    let result = match &search_parameters.name {
23        // Empty search queries should be treated like nonexistent queries.
24        Some(query) if !query.is_empty() => {
25            Plants::search(query, page_parameters, &mut conn).await?
26        }
27        _ => Plants::find_any(page_parameters, &mut conn).await?,
28    };
29
30    Ok(result)
31}
32
33/// Find the plant by id from the database.
34///
35/// # Errors
36/// If the connection to the database could not be established.
37pub async fn find_by_id(id: i32, pool: &SharedPool) -> Result<PlantsSummaryDto, ServiceError> {
38    let mut conn = pool.get().await?;
39    let result = Plants::find_by_id(id, &mut conn).await?;
40    Ok(result)
41}