pub mod impls;
pub mod topology;
pub mod view;
use std::sync::Arc;
use bson::doc;
use mongodb::Client;
pub use topology::Topology;
pub use view::MongoView;
#[derive(Clone, Debug)]
pub struct MongoDB {
client: Client,
database: String,
topology: Topology,
view: Option<Arc<MongoView>>,
}
impl MongoDB {
pub fn new(client: Client, database: impl Into<String>) -> Self {
Self {
client,
database: database.into(),
topology: Topology::Unknown,
view: None,
}
}
pub async fn connect(uri: &str, database: impl Into<String>) -> vantage_core::Result<Self> {
let client = Client::with_uri_str(uri).await.map_err(|e| {
vantage_core::error!("Failed to connect to MongoDB", details = e.to_string())
})?;
let mut mongo = Self::new(client, database);
mongo.topology = match mongo.database().run_command(doc! { "hello": 1 }).await {
Ok(reply) => Topology::from_hello(&reply),
Err(_) => Topology::Unknown,
};
Ok(mongo)
}
pub fn topology(&self) -> Topology {
self.topology
}
pub fn supports_change_streams(&self) -> bool {
self.topology.supports_change_streams()
}
#[cfg(feature = "vista")]
pub(crate) fn client(&self) -> &Client {
&self.client
}
pub fn database(&self) -> mongodb::Database {
self.client.database(&self.database)
}
pub fn collection<T: Send + Sync>(&self, name: &str) -> mongodb::Collection<T> {
self.database().collection(name)
}
pub fn doc_collection(&self, name: &str) -> mongodb::Collection<bson::Document> {
self.database().collection(name)
}
}