Skip to main content

qm_entity/
list.rs

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