mongo_collection/query/
paginated.rs1use serde::{Deserialize, Serialize};
2use smart_default::SmartDefault;
3use std::collections::HashMap;
4
5use crate::query::SortOrder;
6#[cfg(feature = "openapi")]
7use utoipa::{IntoParams, ToSchema};
8
9#[derive(Debug, Clone, SmartDefault, Deserialize)]
11#[cfg_attr(feature = "openapi", derive(ToSchema, IntoParams))]
12#[serde(default)]
13pub struct PaginatedQuery {
14 #[default = 1]
17 pub page: u64,
18 #[default = 10]
20 pub page_size: u64,
21 pub sort_by: Option<String>,
24 #[default(_code = "SortOrder::Desc")]
26 pub sort_order: SortOrder,
27 pub search: Option<String>,
30 #[serde(flatten)]
32 pub filters: Option<HashMap<String, String>>,
33}
34
35impl PaginatedQuery {
36 pub fn parsed_filters(&self) -> Option<HashMap<String, String>> {
37 if let Some(ref raw_filters) = self.filters {
38 let mut filters = HashMap::new();
39 for (key, value) in raw_filters {
40 if let Some(k) = key
42 .strip_prefix("filters[")
43 .and_then(|s| s.strip_suffix("]"))
44 {
45 filters.insert(k.to_string(), value.to_string());
46 }
47 else if let Some(k) = key.strip_prefix("filters.") {
49 filters.insert(k.to_string(), value.to_string());
50 }
51 }
52 return Some(filters);
53 }
54 None
55 }
56}
57
58impl PaginatedQuery {
59 pub fn skip(&self) -> u64 {
61 (self.page - 1) * self.page_size
62 }
63
64 pub fn limit(&self) -> i64 {
66 self.page_size as i64
67 }
68}
69
70#[derive(Debug, Clone, Serialize)]
72#[cfg_attr(feature = "openapi", derive(ToSchema))]
73#[cfg_attr(feature = "openapi", schema(bound = "T: ToSchema"))]
74pub struct PaginatedData<T> {
75 pub items: Vec<T>,
77 pub total_count: u64,
79 pub page: u64,
81 pub page_size: u64,
83 pub total_pages: u64,
85}
86
87impl<T> PaginatedData<T> {
88 pub fn map<P, F>(self, f: F) -> PaginatedData<P>
92 where
93 F: FnMut(T) -> P,
94 {
95 PaginatedData {
96 items: self.items.into_iter().map(f).collect(),
97 total_count: self.total_count,
98 page: self.page,
99 page_size: self.page_size,
100 total_pages: self.total_pages,
101 }
102 }
103
104 pub fn try_map<P, E, F>(self, f: F) -> Result<PaginatedData<P>, E>
108 where
109 F: FnMut(T) -> Result<P, E>,
110 {
111 Ok(PaginatedData {
112 items: self
113 .items
114 .into_iter()
115 .map(f)
116 .collect::<Result<Vec<_>, _>>()?,
117 total_count: self.total_count,
118 page: self.page,
119 page_size: self.page_size,
120 total_pages: self.total_pages,
121 })
122 }
123}