65 lines
1.4 KiB
Rust
Raw Normal View History

#[allow(unused_imports)]
use crate::error::{InternalError, SystemError};
2021-06-27 15:11:41 +08:00
use crate::{
2021-07-06 14:14:47 +08:00
request::EventRequest,
response::{EventResponse, ResponseBuilder},
2021-06-27 15:11:41 +08:00
};
use bytes::Bytes;
2021-06-24 16:32:36 +08:00
pub trait Responder {
2021-06-27 15:11:41 +08:00
fn respond_to(self, req: &EventRequest) -> EventResponse;
2021-06-24 16:32:36 +08:00
}
macro_rules! impl_responder {
($res: ty) => {
impl Responder for $res {
2021-06-30 23:11:27 +08:00
fn respond_to(self, _: &EventRequest) -> EventResponse {
ResponseBuilder::Ok().data(self).build()
2021-06-30 23:11:27 +08:00
}
2021-06-24 16:32:36 +08:00
}
};
}
impl_responder!(&'static str);
impl_responder!(String);
impl_responder!(&'_ String);
impl_responder!(Bytes);
impl<T, E> Responder for Result<T, E>
where
T: Responder,
E: Into<SystemError>,
{
fn respond_to(self, request: &EventRequest) -> EventResponse {
match self {
Ok(val) => val.respond_to(request),
Err(e) => e.into().into(),
}
}
}
pub trait ToBytes {
2021-07-05 16:54:41 +08:00
fn into_bytes(self) -> Result<Vec<u8>, String>;
}
2021-07-05 16:54:41 +08:00
#[cfg(feature = "use_protobuf")]
impl<T> ToBytes for T
where
2021-07-05 16:54:41 +08:00
T: std::convert::TryInto<Vec<u8>, Error = String>,
{
2021-07-05 16:54:41 +08:00
fn into_bytes(self) -> Result<Vec<u8>, String> { self.try_into() }
}
2021-06-30 23:11:27 +08:00
#[cfg(feature = "use_serde")]
impl<T> ToBytes for T
2021-06-30 23:11:27 +08:00
where
T: serde::Serialize,
{
2021-07-05 16:54:41 +08:00
fn into_bytes(self) -> Result<Vec<u8>, String> {
match serde_json::to_string(&self.0) {
Ok(s) => Ok(s.into_bytes()),
2021-07-05 16:54:41 +08:00
Err(e) => Err(format!("{:?}", e)),
}
}
2021-06-30 23:11:27 +08:00
}