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
#[cfg(feature = "graphql")]
#[macro_use]
extern crate juniper;
#[cfg(any(test, feature = "test"))]
#[macro_use]
extern crate lazy_static;

use bson::Document;

mod base;
mod error;
mod id;
mod mongo;
mod node;

pub use crate::error::ServiceError;
use crate::mongo::MongoService;

use mongodb::Collection;
use std::collections::HashMap;

pub use base::{BaseService, DeleteResponse};
pub use id::ID;
pub use node::Node;
pub use node::NodeDetails;

#[cfg(feature = "graphql")]
pub use base::DeleteResponseGQL;

#[cfg(feature = "test")]
pub use base::mock_time;

#[derive(Clone)]
pub struct DataSources {
    collections: HashMap<String, MongoService>,
}

impl DataSources {
    pub fn new() -> Self {
        DataSources {
            collections: HashMap::new(),
        }
    }

    pub fn create_mongo_service(
        &mut self,
        name: &str,
        collection: &Collection,
        default_sort: Option<Document>,
    ) {
        self.collections.insert(
            name.to_string(),
            MongoService::new(collection, default_sort),
        );
    }

    pub fn get_mongo_service(&self, key: &str) -> Result<&MongoService, ServiceError> {
        let service = self.collections.get(&key.to_string());
        match service {
            Some(s) => Ok(s),
            None => Err(ServiceError::ConnectionError(format!(
                "Unable to connect to collection {}",
                key
            ))),
        }
    }
}