use crate::error::oximod_error::OxiModError;
use mongodb::Client;
use std::sync::{Arc, OnceLock};
static CLIENT: OnceLock<Arc<Client>> = OnceLock::new();
pub struct OxiClient {
inner: Option<Client>,
}
impl OxiClient {
pub async fn new(url: String) -> Result<Self, OxiModError> {
let client = Self::connect(url).await?;
Ok(OxiClient {
inner: Some(client),
})
}
async fn connect(mongo_uri: String) -> Result<Client, OxiModError> {
let client = Client::with_uri_str(&mongo_uri).await.map_err(|e| {
OxiModError::connection("Unable to establish MongoDB client from provided URI", e)
})?;
Ok(client)
}
pub async fn init_client(&mut self, mongo_uri: String) -> Result<(), OxiModError> {
let client = Self::connect(mongo_uri).await?;
self.inner = Some(client);
Ok(())
}
pub fn client(&self) -> Option<&Client> {
self.inner.as_ref()
}
pub fn client_mut(&mut self) -> Option<&Client> {
self.inner.as_ref()
}
pub async fn init_global(mongo_uri: String) -> Result<(), OxiModError> {
let client = Self::connect(mongo_uri).await?;
CLIENT.set(client.into()).map_err(|_| {
OxiModError::global_client_init("Global MongoDB client has already been initialized")
})?;
Ok(())
}
pub fn global() -> Result<Arc<Client>, OxiModError> {
CLIENT.get().cloned().ok_or_else(|| {
OxiModError::global_client_missing("Global MongoDB client has not been initialized")
})
}
}