Skip to main content

mongo_collection/query/
list.rs

1use 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/// 列表查询参数
11#[derive(Debug, Clone, SmartDefault, Deserialize)]
12#[cfg_attr(feature = "openapi", derive(ToSchema, IntoParams))]
13#[serde(default)]
14pub struct ListQuery {
15    /// 排序字段(如 "created_at"、"name")
16    pub sort_by: Option<String>,
17    /// 排序方向
18    #[default(_code = "SortOrder::Desc")]
19    pub sort_order: SortOrder,
20    /// 全局搜索关键词
21    pub search: Option<String>,
22    /// 字段级筛选
23    #[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                // 解析 filters[key] 格式
33                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                // 解析 filters.key 格式
40                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/// 列表数据响应
51#[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    /// 数据列表
56    pub items: Vec<T>,
57    /// 总记录数
58    pub total_count: u64,
59}
60
61impl<T> ListData<T> {
62    /// 创建新的列表数据
63    pub fn new(items: Vec<T>) -> Self {
64        Self {
65            total_count: items.len() as u64,
66            items,
67        }
68    }
69
70    /// 转换数据类型
71    ///
72    /// 使用泛型闭包对每个元素进行转换
73    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    /// 转换数据类型(可能失败)
84    ///
85    /// 使用泛型闭包对每个元素进行转换,转换可能失败
86    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}