qm_entity/
list.rs

1use qm_mongodb::bson::Document;
2use serde::de::DeserializeOwned;
3
4use crate::{error::EntityResult, model::ListResult};
5
6pub trait NewList<T>
7where
8    T: DeserializeOwned + Send + Sync + Unpin + 'static,
9{
10    fn new(items: Vec<T>, limit: Option<i64>, total: Option<i64>, page: Option<i64>) -> Self;
11}
12
13pub struct ListCtx<T>
14where
15    T: Send + Sync,
16{
17    collection: crate::Collection<T>,
18    query: Option<Document>,
19}
20
21impl<T> ListCtx<T>
22where
23    T: DeserializeOwned + Send + Sync + Unpin + 'static,
24{
25    pub fn new(collection: crate::Collection<T>) -> Self {
26        Self {
27            collection,
28            query: None,
29        }
30    }
31
32    pub fn with_query(mut self, query: Document) -> Self {
33        self.query = Some(query);
34        self
35    }
36
37    pub async fn list<R>(&mut self, filter: Option<crate::model::ListFilter>) -> EntityResult<R>
38    where
39        R: NewList<T>,
40    {
41        let ListResult {
42            items,
43            limit,
44            total,
45            page,
46        } = self.collection.list(self.query.take(), filter).await?;
47        Ok(R::new(items, limit, total, page))
48    }
49}