diff --git a/src/db/mod.rs b/src/db/mod.rs index 6f3ab70..f0ec585 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -2,6 +2,7 @@ pub mod application; pub mod bots; pub mod callback_info; pub mod message_forward; +pub mod raw_calls; use std::time::Duration; diff --git a/src/db/raw_calls.rs b/src/db/raw_calls.rs new file mode 100644 index 0000000..36488fd --- /dev/null +++ b/src/db/raw_calls.rs @@ -0,0 +1,38 @@ +use mongodb::Database; + +use super::CallDB; +use serde_json::Value; + +#[derive(thiserror::Error, Debug)] +pub enum RawCallError { + #[error("error while processing mongodb query: {0}")] + MongodbError(#[from] mongodb::error::Error), + #[error("error while buildint bson's query document: {0}")] + DocumentError(#[from] mongodb::bson::extjson::de::Error), + #[error("error when expected map: {0}")] + NotAMapError(String), +} +pub type RawCallResult = Result; + +pub trait RawCall { + async fn get_database(&mut self) -> Database; + async fn find_one(&mut self, collection: &str, query: Value) -> RawCallResult> { + let db = self.get_database().await; + let value = db.collection::(collection); + + let map = match query { + Value::Object(map) => map, + _ => return Err(RawCallError::NotAMapError("query is not a map".to_string())), + }; + + let doc = map.try_into()?; + let ret = value.find_one(doc).await?; + Ok(ret) + } +} + +impl RawCall for T { + async fn get_database(&mut self) -> Database { + CallDB::get_database(self).await + } +}