mongo_orm/
repo.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use crate::entity::MongoEntity;
use async_trait::async_trait;
use futures::TryStreamExt;
use mongodb::options::FindOptions;
use mongodb::{
    bson::{doc, oid::ObjectId, Document},
    Collection,
};

use typed_builder::TypedBuilder;

#[async_trait]
pub trait MongoRepository<E> {
    async fn find_by_id(&self, id: &str) -> Option<E>;

    async fn insert(&self, entity: &E) -> String;

    async fn insert_many(&self, entities: &[E]);

    async fn update_by_id(&self, id: &str, update: Document);

    async fn update_one_by(&self, filter: Document, update: Document);

    async fn update_many(&self, filter: Document, update: Document) -> (u64, u64);

    async fn delete_by_id(&self, id: &str) -> bool;

    async fn find(&self, option: FindOption) -> Vec<E>;

    async fn find_one_by(&self, filter: Document) -> Option<E>;

    async fn count(&self, filter: Option<Document>) -> u64;

    async fn exists(&self, filter: Document) -> bool;

    async fn delete_by(&self, filter: Document) -> u64;

    async fn aggregate(&self, stages: Vec<Document>) -> Vec<Document>;
}

impl<E: MongoEntity> MongoRepo<E> {
    pub fn new(collection: Collection<Document>) -> Self {
        Self {
            collection,
            entity: Default::default(),
        }
    }
}
#[derive(Debug)]
pub struct MongoRepo<E: MongoEntity> {
    collection: Collection<Document>,
    entity: std::marker::PhantomData<E>,
}

#[derive(Debug, TypedBuilder, Clone)]
pub struct FindOption {
    #[builder(default, setter(strip_option))] // Optional field, allows None or Some(Document)
    pub filter: Option<Document>,

    #[builder(default, setter(strip_option))] // Optional field
    pub sort: Option<Document>,

    #[builder(default, setter(strip_option))] // Optional field
    pub limit: Option<i64>,

    #[builder(default, setter(strip_option))] // Optional field
    pub skip: Option<u64>,
}

impl FindOption {
    pub fn all() -> Self {
        FindOption {
            filter: None,
            sort: None,
            limit: None,
            skip: None,
        }
    }
}

impl Into<FindOptions> for FindOption {
    fn into(self) -> FindOptions {
        let mut builder = FindOptions::default();

        builder.sort = self.sort;
        builder.skip = self.skip;
        builder.limit = self.limit;

        builder
    }
}

#[async_trait]
impl<E> MongoRepository<E> for MongoRepo<E>
where
    E: MongoEntity,
{
    async fn find_by_id(&self, id: &str) -> Option<E> {
        let object_id = ObjectId::parse_str(id);

        let find = match object_id {
            Ok(oid) => self.collection.find_one(doc! { "_id": oid }),
            Err(_) => self.collection.find_one(doc! { "_id": id }),
        };

        find.await.unwrap().map(E::from_document)
    }

    async fn insert(&self, entity: &E) -> String {
        let id = self
            .collection
            .insert_one(entity.to_document())
            .await
            .unwrap()
            .inserted_id;

        if let Some(oid) = id.as_object_id() {
            oid.to_hex()
        } else {
            id.to_string()
        }
    }

    async fn insert_many(&self, entities: &[E]) {
        let documents: Vec<Document> = entities.iter().map(|e| e.to_document()).collect();
        self.collection.insert_many(documents).await.unwrap();
    }

    async fn update_by_id(&self, id: &str, update: Document) {
        let f = ObjectId::parse_str(id)
            .map(|oid| doc! { "_id": oid })
            .unwrap_or(doc! { "_id": id });
        self.collection
            .update_one(f, doc! { "$set": update })
            .await
            .unwrap();
    }

    async fn update_one_by(&self, filter: Document, update: Document) {
        self.collection
            .update_one(filter, doc! { "$set": update })
            .await
            .unwrap();
    }

    async fn update_many(&self, filter: Document, update: Document) -> (u64, u64) {
        let result = self
            .collection
            .update_many(filter, doc! { "$set": update })
            .await
            .unwrap();
        (result.matched_count, result.modified_count)
    }

    async fn delete_by_id(&self, id: &str) -> bool {
        let object_id = ObjectId::parse_str(id).unwrap();
        let result = self
            .collection
            .delete_one(doc! { "_id": object_id })
            .await
            .unwrap();
        result.deleted_count > 0
    }

    async fn find(&self, option: FindOption) -> Vec<E> {
        let options: FindOptions = option.clone().into();
        let mut cursor = self
            .collection
            .find(option.filter.unwrap_or(doc! {}))
            .with_options(options)
            .await
            .unwrap();
        let mut results = Vec::new();
        while let Some(doc) = cursor.try_next().await.unwrap() {
            results.push(E::from_document(doc));
        }
        results
    }

    async fn find_one_by(&self, filter: Document) -> Option<E> {
        self.collection
            .find_one(filter)
            .await
            .unwrap()
            .map(E::from_document)
    }

    async fn count(&self, filter: Option<Document>) -> u64 {
        self.collection
            .count_documents(filter.unwrap_or_default())
            .await
            .unwrap()
    }

    async fn exists(&self, filter: Document) -> bool {
        self.collection.count_documents(filter).await.unwrap() > 0
    }

    async fn delete_by(&self, filter: Document) -> u64 {
        let result = self.collection.delete_many(filter).await.unwrap();
        result.deleted_count
    }

    async fn aggregate(&self, stages: Vec<Document>) -> Vec<Document> {
        let cursor = self.collection.aggregate(stages).await.unwrap();
        cursor.try_collect().await.unwrap()
    }
}