use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
use std::collections::HashMap;
use crate::query::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>,
#[serde(flatten)]
pub filters: Option<HashMap<String, String>>,
}
impl ListQuery {
pub fn parsed_filters(&self) -> Option<HashMap<String, String>> {
if let Some(ref raw_filters) = self.filters {
let mut filters = HashMap::new();
for (key, value) in raw_filters {
if let Some(k) = key
.strip_prefix("filters[")
.and_then(|s| s.strip_suffix("]"))
{
filters.insert(k.to_string(), value.to_string());
}
else if let Some(k) = key.strip_prefix("filters.") {
filters.insert(k.to_string(), value.to_string());
}
}
return Some(filters);
}
None
}
}
#[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,
})
}
}