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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use bson::{doc, Bson, Document};

use chrono::Utc;
use log::warn;
use mongodb::options::FindOptions;
use mongodb::Collection;
use mongodb_cursor_pagination::{CursorDirections, FindResult, PaginatedCursor};
use serde::{Deserialize, Serialize};
use voca_rs::case::snake_case;

use crate::error::ServiceError;
use crate::model::ID;

#[derive(Serialize, Deserialize)]
pub struct DeleteResponse {
    id: ID,
    success: bool,
}

#[cfg(feature = "graphql")]
#[derive(Serialize, Deserialize, juniper::GraphQLObject)]
pub struct DeleteResponseGQL {
    id: juniper::ID,
    success: bool,
}

#[cfg(feature = "graphql")]
impl From<DeleteResponse> for DeleteResponseGQL {
    fn from(d: DeleteResponse) -> DeleteResponseGQL {
        DeleteResponseGQL {
            id: d.id.into(),
            success: d.success,
        }
    }
}

use crate::model::Node;

const DEFAULT_LIMIT: i64 = 25;

fn now() -> i64 {
    Utc::now().timestamp()
}

fn get_id_str(id: &Option<ID>) -> String {
    id.clone().unwrap_or(ID::new("unknown")).to_string()
}

pub trait BaseService<'a> {
    fn new(collection: &Collection, default_sort: Option<Document>) -> Self;
    fn id_parameter(&self) -> &'static str {
        "node.id"
    }
    fn data_source(&self) -> &Collection;
    fn default_sort(&self) -> Document {
        doc! { "_id": 1 }
    }
    fn default_filter(&self) -> Option<&Document> {
        None
    }
    fn default_limit(&self) -> i64 {
        DEFAULT_LIMIT
    }

    fn find<T>(
        &self,
        filter: Option<Document>,
        sort: Option<Document>,
        limit: Option<i32>,
        after: Option<String>,
        before: Option<String>,
        skip: Option<i32>,
    ) -> Result<FindResult<T>, ServiceError>
    where
        T: serde::Deserialize<'a>,
    {
        let coll = self.data_source();
        // build the options object
        let find_options = FindOptions::builder()
            .limit(if let Some(l) = limit {
                l as i64
            } else {
                self.default_limit()
            })
            .skip(if let Some(s) = skip { s as i64 } else { 0 })
            // TODO: make this not something arbitrary for testing purposes
            .sort(if let Some(s) = sort {
                s
            } else {
                self.default_sort()
            })
            .build();
        let is_previous_query = before.is_some() && after.is_none();
        let query_cursor = if is_previous_query {
            PaginatedCursor::new(Some(find_options), before, Some(CursorDirections::Previous))
        } else {
            PaginatedCursor::new(Some(find_options), after, None)
        };
        let find_results: FindResult<T> = if let Some(f) = filter {
            query_cursor.find(&coll, Some(&f))?
        } else {
            query_cursor.find(&coll, self.default_filter())?
        };
        Ok(find_results)
    }

    fn search<T>(
        &self,
        search_term: String,
        fields: Vec<String>,
        sort: Option<Document>,
        limit: Option<i32>,
        after: Option<String>,
        before: Option<String>,
        skip: Option<i32>,
    ) -> Result<FindResult<T>, ServiceError>
    where
        T: serde::Deserialize<'a>,
    {
        let coll = self.data_source();
        // build the options object
        let find_options = FindOptions::builder()
            .limit(if let Some(l) = limit {
                l as i64
            } else {
                self.default_limit()
            })
            .skip(if let Some(s) = skip { s as i64 } else { 0 })
            // TODO: make this not something arbitrary for testing purposes
            .sort(if let Some(s) = sort {
                s
            } else {
                self.default_sort()
            })
            .build();
        let is_previous_query = before.is_some() && after.is_none();
        let query_cursor = if is_previous_query {
            PaginatedCursor::new(Some(find_options), before, Some(CursorDirections::Previous))
        } else {
            PaginatedCursor::new(Some(find_options), after, None)
        };
        let mut filter = doc! { "$or": [] };
        let or_array = filter.get_array_mut("$or").unwrap();
        for field in fields.iter().map(|f| snake_case(&f)) {
            or_array.push(Bson::Document(
                doc! { field: Bson::RegExp(search_term.clone(), "i".to_string()) },
            ));
        }
        let find_results: FindResult<T> = query_cursor.find(&coll, Some(&filter))?;
        Ok(find_results)
    }

    fn find_one_by_id<T>(&self, id: ID) -> Result<Option<T>, ServiceError>
    where
        T: serde::Deserialize<'a>,
    {
        self.find_one_by_string_value(self.id_parameter(), &id.to_string())
    }

    fn find_one_by_string_value<T>(
        &self,
        field: &str,
        value: &str,
    ) -> Result<Option<T>, ServiceError>
    where
        T: serde::Deserialize<'a>,
    {
        let coll = self.data_source();
        let query = Some(doc! { field => value });
        let find_result = coll.find_one(query, None)?;
        match find_result {
            Some(item_doc) => {
                let doc = bson::from_bson(bson::Bson::Document(item_doc))?;
                Ok(Some(doc))
            }
            None => Ok(None),
        }
    }

    fn find_one_by_i64<T>(&self, field: &str, value: i64) -> Result<Option<T>, ServiceError>
    where
        T: serde::Deserialize<'a>,
    {
        let coll = self.data_source();
        let query = Some(doc! { field => value });
        let find_result = coll.find_one(query, None)?;
        match find_result {
            Some(item_doc) => {
                let doc = bson::from_bson(bson::Bson::Document(item_doc))?;
                Ok(Some(doc))
            }
            None => Ok(None),
        }
    }

    fn insert_embedded<T, U>(
        &self,
        id: ID,
        field_path: &str,
        new_items: Vec<T>,
        user_id: Option<ID>,
    ) -> Result<U, ServiceError>
    where
        T: serde::Serialize,
        U: serde::Deserialize<'a>,
    {
        // get the item
        let coll = self.data_source();
        let query = doc! { self.id_parameter(): &id.to_string() };
        let find_result = coll.find_one(Some(query.clone()), None).unwrap();

        match find_result {
            None => Err(ServiceError::NotFound("Unable to find item".into())),
            Some(_item) => {
                // insert it
                let serialized_members = new_items.iter().fold(Vec::new(), |mut acc, item| {
                    match bson::to_bson(&item) {
                        Ok(serialized_member) => {
                            if let bson::Bson::Document(mut document) = serialized_member {
                                let mut node_details = Document::new();
                                node_details
                                    .insert("id", uuid::Uuid::new_v4().to_hyphenated().to_string());
                                node_details.insert("date_created", now());
                                node_details.insert("date_modified", now());
                                node_details.insert("created_by_id", get_id_str(&user_id));
                                node_details.insert("updated_by_id", get_id_str(&user_id));
                                document.insert("node", node_details);
                                acc.push(document);
                            }
                        }
                        Err(_) => warn!("Unable to insert item"),
                    }
                    acc
                });

                let update_doc = doc! { "$push": { field_path: { "$each": serialized_members } } };
                let _result = coll.update_one(query, update_doc, None);
                let item_doc =
                    coll.find_one(Some(doc! { self.id_parameter() => &id.to_string() }), None)?;
                match item_doc {
                    Some(i) => {
                        let item: U = bson::from_bson(bson::Bson::Document(i))?;
                        Ok(item)
                    }
                    None => Err(ServiceError::NotFound("Unable to find document".into())),
                }
            }
        }
    }

    fn insert_one<T, U>(&self, new_item: T, user_id: Option<ID>) -> Result<U, ServiceError>
    where
        T: serde::Serialize,
        U: serde::Deserialize<'a> + Node,
    {
        let coll = self.data_source();
        let serialized_member = bson::to_bson(&new_item)?;

        if let bson::Bson::Document(mut document) = serialized_member {
            let mut node_details = Document::new();
            node_details.insert("id", uuid::Uuid::new_v4().to_hyphenated().to_string());
            node_details.insert("date_created", now());
            node_details.insert("date_modified", now());
            node_details.insert("created_by_id", get_id_str(&user_id));
            node_details.insert("updated_by_id", get_id_str(&user_id));
            document.insert("node", node_details);
            let result = coll.insert_one(document, None)?; // Insert into a MongoDB collection
            let id = result.inserted_id;
            let item_doc = coll
                .find_one(Some(doc! { "_id" => id }), None)?
                .expect("Document not found");

            let item: U = bson::from_bson(bson::Bson::Document(item_doc))?;
            Ok(item)
        } else {
            warn!("Error converting the BSON object into a MongoDB document");
            Err(ServiceError::ParseError(
                "Error converting the BSON object into a MongoDB document".into(),
            ))
        }
    }

    fn insert_many<T, U>(
        &self,
        new_items: Vec<T>,
        user_id: Option<ID>,
    ) -> Result<Vec<U>, ServiceError>
    where
        T: serde::Serialize,
        U: serde::Deserialize<'a> + Node,
    {
        let coll = self.data_source();

        let serialized_members = new_items.iter().fold(Vec::new(), |mut acc, item| {
            match bson::to_bson(&item) {
                Ok(serialized_member) => {
                    if let bson::Bson::Document(mut document) = serialized_member {
                        let mut node_details = Document::new();
                        node_details.insert("id", uuid::Uuid::new_v4().to_hyphenated().to_string());
                        node_details.insert("date_created", now());
                        node_details.insert("date_modified", now());
                        node_details.insert("created_by_id", get_id_str(&user_id));
                        node_details.insert("updated_by_id", get_id_str(&user_id));
                        document.insert("node", node_details);
                        acc.push(document);
                    }
                }
                Err(_) => warn!("Unable to insert item"),
            }
            acc
        });

        let result = coll.insert_many(serialized_members, None)?;
        let ids: Vec<&Bson> = result.inserted_ids.values().collect();

        let filter = doc! { "_id": { "$in": ids } };
        let items_cursor: mongodb::Cursor = coll.find(Some(filter), None)?;
        let mut items: Vec<U> = vec![];
        for result in items_cursor {
            match result {
                Ok(doc) => {
                    let item: U = bson::from_bson(bson::Bson::Document(doc.clone())).unwrap();
                    items.push(item);
                }
                Err(error) => {
                    warn!("Error to find inserted doc: {}", error);
                }
            }
        }
        Ok(items)
    }

    fn delete_one_by_id(&self, id: ID) -> Result<DeleteResponse, ServiceError> {
        let coll = self.data_source();
        let filter = doc! { self.id_parameter(): id.to_string() };
        let result = coll.delete_one(filter, None);
        match result {
            Ok(r) => Ok(DeleteResponse {
                id,
                success: r.deleted_count == 1,
            }),
            Err(e) => Err(e.into()),
        }
    }

    fn delete_one_by_query(&self, filter: Document) -> Result<bool, ServiceError> {
        let coll = self.data_source();
        let result = coll.delete_one(filter, None);
        match result {
            Ok(r) => Ok(r.deleted_count == 1),
            Err(e) => Err(e.into()),
        }
    }

    fn delete_embedded(
        &self,
        id: ID,
        field_path: &str,
        embedded_id: ID,
    ) -> Result<DeleteResponse, ServiceError> {
        let coll = self.data_source();
        let query = doc! { self.id_parameter(): &id.to_string() };
        let update_doc =
            doc! { "$pull": { field_path: { self.id_parameter(): &embedded_id.to_string()} } };
        let _result = coll.update_one(query, update_doc, None)?;
        Ok(DeleteResponse {
            id: embedded_id,
            success: true,
        })
    }

    fn update_embedded<T, U>(
        &self,
        id: ID,
        field_path: &str,
        embedded_id: ID,
        update_item: T,
        user_id: Option<ID>,
    ) -> Result<U, ServiceError>
    where
        T: serde::Serialize,
        U: serde::Deserialize<'a>,
    {
        let coll = self.data_source();
        let search_embedded = doc! {
            self.id_parameter(): &id.to_string(),
            format!("{}.{}", field_path, self.id_parameter()): &embedded_id.to_string(),
        };
        let serialized_member = bson::to_bson(&update_item)?;
        if let bson::Bson::Document(document) = serialized_member {
            let array_path = format!("{}.$", field_path);
            let mut update_doc = Document::new();
            for key in document.keys() {
                let value = document.get(key);
                if let Some(v) = value {
                    update_doc.insert(format!("{}.{}", array_path, key), v.clone());
                }
            }
            update_doc.insert(format!("{}.node.date_modified", array_path), now());
            update_doc.insert(
                format!("{}.node.updated_by_id", array_path),
                get_id_str(&user_id),
            );
            let update = doc! { "$set": update_doc };
            let search = doc! { self.id_parameter(): &id.to_string() };
            match coll.update_one(search_embedded, update, None) {
                Ok(_res) => match coll.find_one(Some(search), None) {
                    Ok(res) => match res {
                        Some(doc) => {
                            let item: U = bson::from_bson(bson::Bson::Document(doc))?;
                            Ok(item)
                        }
                        None => Err(ServiceError::NotFound("Unable to find item".to_owned())),
                    },
                    Err(t) => {
                        warn!("Search failed");
                        Err(ServiceError::from(t))
                    }
                },
                Err(e) => Err(ServiceError::from(e)),
            }
        } else {
            Err("Unable to update document".into())
        }
    }

    fn update_one<T, U>(
        &self,
        id: ID,
        update_item: T,
        user_id: Option<ID>,
    ) -> Result<U, ServiceError>
    where
        T: serde::Serialize,
        U: serde::Deserialize<'a> + Node,
    {
        let coll = self.data_source();
        let search = doc! { self.id_parameter(): id.to_string() };
        let serialized_member = bson::to_bson(&update_item)?;
        if let bson::Bson::Document(mut document) = serialized_member {
            document.insert("node.date_modified", now());
            document.insert("node.updated_by_id", get_id_str(&user_id));
            match coll.update_one(search.clone(), doc! {"$set": document}, None) {
                Ok(_res) => match coll.find_one(Some(search), None) {
                    Ok(res) => match res {
                        Some(doc) => {
                            let item: U = bson::from_bson(bson::Bson::Document(doc))?;
                            Ok(item)
                        }
                        None => Err(ServiceError::NotFound("Unable to find item".to_owned())),
                    },
                    Err(t) => {
                        warn!("Search failed");
                        Err(ServiceError::from(t))
                    }
                },
                Err(e) => Err(ServiceError::from(e)),
            }
        } else {
            Err("Invalid update document".into())
        }
    }

    fn update_one_with_doc<U>(&self, id: ID, update_doc: Document) -> Result<U, ServiceError>
    where
        U: serde::Deserialize<'a>,
    {
        let coll = self.data_source();
        let search = doc! { self.id_parameter(): id.to_string() };
        match coll.update_one(search.clone(), update_doc, None) {
            Ok(_res) => match coll.find_one(Some(search), None) {
                Ok(res) => match res {
                    Some(doc) => {
                        let item: U = bson::from_bson(bson::Bson::Document(doc))?;
                        Ok(item)
                    }
                    None => Err(ServiceError::NotFound("Unable to find item".to_owned())),
                },
                Err(t) => {
                    warn!("Search failed");
                    Err(ServiceError::from(t))
                }
            },
            Err(e) => Err(ServiceError::from(e)),
        }
    }
}