create CallbackInfo and its tests

This commit is contained in:
Akulij 2025-04-29 17:37:20 +03:00
parent 0973499652
commit 078e2fd62a
4 changed files with 88 additions and 0 deletions

57
src/db/callback_info.rs Normal file
View File

@ -0,0 +1,57 @@
use crate::query_call;
use crate::CallDB;
use bson::oid::ObjectId;
use serde::{Deserialize, Serialize};
use super::DbResult;
use bson::doc;
#[derive(Serialize, Deserialize, Default)]
pub struct CallbackInfo<C>
where
C: Serialize,
{
pub _id: bson::oid::ObjectId,
#[serde(flatten)]
pub callback: C,
}
impl<C> CallbackInfo<C>
where
C: Serialize + for<'a> Deserialize<'a> + Send + Sync,
{
pub fn new(callback: C) -> Self {
Self {
_id: Default::default(),
callback,
}
}
pub fn get_id(&self) -> String {
self._id.to_hex()
}
query_call!(store, self, db, (), {
let db = db.get_database().await;
let ci = db.collection::<Self>("callback_info");
ci.insert_one(self).await?;
Ok(())
});
pub async fn get<D: CallDB>(db: &mut D, id: &str) -> DbResult<Option<Self>> {
let db = db.get_database().await;
let ci = db.collection::<Self>("callback_info");
let id = match ObjectId::parse_str(id) {
Ok(id) => id,
Err(_) => return Ok(None),
};
ci.find_one(doc! {
"_id": id
})
.await
}
}

View File

@ -1,3 +1,5 @@
pub mod callback_info;
use async_trait::async_trait; use async_trait::async_trait;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use enum_stringify::EnumStringify; use enum_stringify::EnumStringify;

View File

@ -0,0 +1,28 @@
use super::super::{callback_info::CallbackInfo, CallDB, DB};
use super::setup_db;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Default)]
#[serde(tag = "type")]
#[serde(rename = "snake_case")]
pub enum Callback {
#[default]
MoreInfo,
NextPage,
}
type CI = CallbackInfo<Callback>;
#[tokio::test]
async fn test_store() {
let mut db = setup_db().await;
let ci = CI::new(Default::default());
ci.store(&mut db).await.unwrap();
let ci = CI::get(&mut db, &ci.get_id()).await.unwrap();
assert!(ci.is_some());
}

View File

@ -1,5 +1,6 @@
#![allow(clippy::unwrap_used)] #![allow(clippy::unwrap_used)]
mod callback_info_tests;
use dotenvy; use dotenvy;
use super::CallDB; use super::CallDB;