return custom error in src/mongodb_storage.rs to support return of serializer error

This commit is contained in:
Akulij 2025-04-28 22:41:21 +03:00
parent 55d393eb2c
commit c11e671b15

View File

@ -36,6 +36,26 @@ pub struct Dialogue {
dialogue: Vec<u32>, dialogue: Vec<u32>,
} }
#[derive(Debug, thiserror::Error)]
pub enum MongodbStorageError<SE>
where
SE: Debug + Display,
{
MongodbError(#[from] mongodb::error::Error),
SerdeError(SE),
}
pub type MongodbStorageResult<T, SE> = Result<T, MongodbStorageError<SE>>;
impl<SE> std::fmt::Display for MongodbStorageError<SE>
where
SE: Debug + Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl<S, D> Storage<D> for MongodbStorage<S> impl<S, D> Storage<D> for MongodbStorage<S>
where where
S: Send + Sync + Serializer<D> + 'static, S: Send + Sync + Serializer<D> + 'static,
@ -43,7 +63,7 @@ where
<S as Serializer<D>>::Error: Debug + Display, <S as Serializer<D>>::Error: Debug + Display,
{ {
type Error = mongodb::error::Error; type Error = MongodbStorageError<<S as Serializer<D>>::Error>;
fn remove_dialogue( fn remove_dialogue(
self: std::sync::Arc<Self>, self: std::sync::Arc<Self>,
@ -56,7 +76,8 @@ where
let d = self.database.collection::<Dialogue>("dialogues"); let d = self.database.collection::<Dialogue>("dialogues");
d.delete_one(doc! { "chat_id": chat_id.0 }) d.delete_one(doc! { "chat_id": chat_id.0 })
.await .await
.map(|_| ()) .map(|_| ())?;
Ok(())
}) })
} }
@ -76,9 +97,14 @@ where
}, },
doc! { doc! {
"$set": doc! { "$set": doc! {
"dialogue": self.serializer.serialize(&dialogue).unwrap().into_iter().map(|v| v as u32).collect::<Vec<u32>>() "dialogue": self.serializer.serialize(&dialogue)
.map_err(MongodbStorageError::SerdeError)?
.into_iter().map(|v| v as u32).collect::<Vec<u32>>()
} }
}).upsert(true).await?; },
)
.upsert(true)
.await?;
Ok(()) Ok(())
}) })
} }
@ -89,8 +115,13 @@ where
) -> BoxFuture<'static, Result<Option<D>, Self::Error>> { ) -> BoxFuture<'static, Result<Option<D>, Self::Error>> {
Box::pin(async move { Box::pin(async move {
let d = self.database.collection::<Dialogue>("dialogues"); let d = self.database.collection::<Dialogue>("dialogues");
Ok(d.find_one(doc! { "chat_id": chat_id.0 }).await?.map(|d| { let d = d.find_one(doc! { "chat_id": chat_id.0 }).await?;
self.serializer let d = match d {
Some(d) => d,
None => return Ok(None),
};
let d = self
.serializer
.deserialize( .deserialize(
d.dialogue d.dialogue
.into_iter() .into_iter()
@ -98,8 +129,9 @@ where
.collect::<Vec<_>>() .collect::<Vec<_>>()
.as_slice(), .as_slice(),
) )
.unwrap() .map_err(MongodbStorageError::SerdeError)?;
}))
Ok(Some(d))
}) })
} }
} }