use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
use std::collections::HashMap;
use crate::SortOrder;
#[cfg(feature = "openapi")]
use utoipa::{IntoParams, ToSchema};
#[derive(Debug, Clone, SmartDefault, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema, IntoParams))]
#[serde(default)]
pub struct ListQuery {
pub sort_by: Option<String>,
#[default(_code = "SortOrder::Desc")]
pub sort_order: SortOrder,
pub search: Option<String>,
pub filters: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(bound = "T: ToSchema"))]
pub struct ListData<T> {
pub items: Vec<T>,
pub total_count: u64,
}
impl<T> ListData<T> {
pub fn new(items: Vec<T>) -> Self {
Self {
total_count: items.len() as u64,
items,
}
}
pub fn map<P, F>(self, f: F) -> ListData<P>
where
F: FnMut(T) -> P,
{
ListData {
items: self.items.into_iter().map(f).collect(),
total_count: self.total_count,
}
}
pub fn try_map<P, E, F>(self, f: F) -> Result<ListData<P>, E>
where
F: FnMut(T) -> Result<P, E>,
{
Ok(ListData {
items: self
.items
.into_iter()
.map(f)
.collect::<Result<Vec<_>, _>>()?,
total_count: self.total_count,
})
}
}