mongo_collection/query/
list.rs1use serde::{Deserialize, Serialize};
2use smart_default::SmartDefault;
3use std::collections::HashMap;
4
5use crate::query::SortOrder;
6
7#[cfg(feature = "openapi")]
8use utoipa::{IntoParams, ToSchema};
9
10#[derive(Debug, Clone, SmartDefault, Deserialize)]
12#[cfg_attr(feature = "openapi", derive(ToSchema, IntoParams))]
13#[serde(default)]
14pub struct ListQuery {
15 pub sort_by: Option<String>,
17 #[default(_code = "SortOrder::Desc")]
19 pub sort_order: SortOrder,
20 pub search: Option<String>,
22 #[serde(flatten)]
24 pub filters: Option<HashMap<String, String>>,
25}
26
27impl ListQuery {
28 pub fn parsed_filters(&self) -> Option<HashMap<String, String>> {
29 if let Some(ref raw_filters) = self.filters {
30 let mut filters = HashMap::new();
31 for (key, value) in raw_filters {
32 if let Some(k) = key
34 .strip_prefix("filters[")
35 .and_then(|s| s.strip_suffix("]"))
36 {
37 filters.insert(k.to_string(), value.to_string());
38 }
39 else if let Some(k) = key.strip_prefix("filters.") {
41 filters.insert(k.to_string(), value.to_string());
42 }
43 }
44 return Some(filters);
45 }
46 None
47 }
48}
49
50#[derive(Debug, Clone, Serialize)]
52#[cfg_attr(feature = "openapi", derive(ToSchema))]
53#[cfg_attr(feature = "openapi", schema(bound = "T: ToSchema"))]
54pub struct ListData<T> {
55 pub items: Vec<T>,
57 pub total_count: u64,
59}
60
61impl<T> ListData<T> {
62 pub fn new(items: Vec<T>) -> Self {
64 Self {
65 total_count: items.len() as u64,
66 items,
67 }
68 }
69
70 pub fn map<P, F>(self, f: F) -> ListData<P>
74 where
75 F: FnMut(T) -> P,
76 {
77 ListData {
78 items: self.items.into_iter().map(f).collect(),
79 total_count: self.total_count,
80 }
81 }
82
83 pub fn try_map<P, E, F>(self, f: F) -> Result<ListData<P>, E>
87 where
88 F: FnMut(T) -> Result<P, E>,
89 {
90 Ok(ListData {
91 items: self
92 .items
93 .into_iter()
94 .map(f)
95 .collect::<Result<Vec<_>, _>>()?,
96 total_count: self.total_count,
97 })
98 }
99}