use std::sync::Arc;
pub use mongodb::{options::ClientOptions, Client};
use crate::{StoreError, DEFAUTL_NAMESPACE_NAME};
use super::MongoStore;
pub struct MongoStoreBuilder {
uri: Option<String>,
database_name: Option<String>,
collection_name: Option<String>,
client: Option<Arc<Client>>,
}
impl MongoStoreBuilder {
pub fn new() -> Self {
Self {
uri: None,
database_name: None,
collection_name: None,
client: None,
}
}
pub fn uri<S: Into<String>>(mut self, uri: S) -> Self {
self.uri = Some(uri.into());
self
}
pub fn database_name<S: Into<String>>(mut self, database_name: S) -> Self {
self.database_name = Some(database_name.into());
self
}
pub fn collection_name<S: Into<String>>(mut self, collection_name: S) -> Self {
self.collection_name = Some(collection_name.into());
self
}
pub fn client(mut self, client: Arc<Client>) -> Self {
self.client = Some(client);
self
}
pub async fn build(self) -> Result<MongoStore, StoreError> {
let client = match self.client {
Some(client) => client,
None => {
let uri = self
.uri
.expect("MongoDB requires a URI or an existing client to be set");
let options = ClientOptions::parse(&uri)
.await
.map_err(|e| StoreError::ConnectionError(e.to_string()))?;
Arc::new(
Client::with_options(options)
.map_err(|e| StoreError::ConnectionError(e.to_string()))?,
)
}
};
let database_name = match &self.database_name {
Some(db_name) => db_name.to_string(),
None => {
log::warn!("Database name not provided, using default");
DEFAUTL_NAMESPACE_NAME.to_string()
}
};
let collection_name = match &self.collection_name {
Some(coll_name) => coll_name.to_string(),
None => {
log::warn!("Collection name not provided, using default");
DEFAUTL_NAMESPACE_NAME.to_string()
}
};
Ok(MongoStore {
client,
database_name,
collection_name,
})
}
}