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
use crate::Collection;
use mongodb::{
    error::Result,
    options::{ClientOptions, Compressor},
    Client,
};
use std::{sync::Arc, time::Duration};

#[derive(Clone, Debug)]
pub struct Mungos {
    pub client: Client,
}

impl Mungos {
    pub async fn new(
        uri: &str,
        app_name: &str,
        timeout: Duration,
        compressors: impl Into<Option<Vec<Compressor>>>,
    ) -> Result<Mungos> {
        // Parse your connection string into an options struct
        let mut client_options = ClientOptions::parse(uri).await?;
        // Manually set an option
        client_options.app_name = Some(app_name.to_string());
        client_options.connect_timeout = Some(timeout);
        client_options.compressors = compressors.into();
        // Get a handle to the cluster
        let client = Client::with_options(client_options)?;
        // println!();
        // println!("============================");
        // println!("==== connected to mongo ====");
        // println!("============================");
        // println!();
        let mungos = Mungos { client };
        Ok(mungos)
    }

    pub fn collection<T>(&self, db_name: &str, collection_name: &str) -> Collection<T> {
        let db = self.client.database(db_name);
        let collection = db.collection(collection_name);
        Collection { db, collection }
    }

    pub fn arc_collection<T>(&self, db_name: &str, collection_name: &str) -> Arc<Collection<T>> {
        let db = self.client.database(db_name);
        let collection = db.collection(collection_name);
        Arc::new(Collection { db, collection })
    }

    pub async fn list_collections(&self, db_name: &str) -> Result<Vec<String>> {
        self.client
            .database(db_name)
            .list_collection_names(None)
            .await
    }
}