1use qm_mongodb::bson::Document;
2use serde::de::DeserializeOwned;
3
4use crate::{error::EntityResult, model::ListResult};
5
6pub trait NewList<T>
8where
9 T: DeserializeOwned + Send + Sync + Unpin + 'static,
10{
11 fn new(items: Vec<T>, limit: Option<i64>, total: Option<i64>, page: Option<i64>) -> Self;
13}
14
15pub 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 pub fn new(collection: crate::Collection<T>) -> Self {
30 Self {
31 collection,
32 query: None,
33 }
34 }
35
36 pub fn with_query(mut self, query: Document) -> Self {
38 self.query = Some(query);
39 self
40 }
41
42 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}