create RawCall trait, that will contain DB methods to call from script runtime

This commit is contained in:
Akulij 2025-05-26 20:22:46 +05:00
parent a33d4b393c
commit cb7c888028
2 changed files with 39 additions and 0 deletions

View File

@ -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;

38
src/db/raw_calls.rs Normal file
View File

@ -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<T> = Result<T, RawCallError>;
pub trait RawCall {
async fn get_database(&mut self) -> Database;
async fn find_one(&mut self, collection: &str, query: Value) -> RawCallResult<Option<Value>> {
let db = self.get_database().await;
let value = db.collection::<Value>(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<T: CallDB> RawCall for T {
async fn get_database(&mut self) -> Database {
CallDB::get_database(self).await
}
}