2021-07-03 23:14:38 +08:00
|
|
|
#[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,
|
2021-07-01 15:40:26 +08:00
|
|
|
response::{EventResponse, ResponseBuilder},
|
2021-06-27 15:11:41 +08:00
|
|
|
};
|
2021-06-29 16:52:29 +08:00
|
|
|
use bytes::Bytes;
|
2021-07-02 20:45:51 +08:00
|
|
|
|
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 {
|
2021-07-01 15:40:26 +08:00
|
|
|
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);
|
2021-06-29 16:52:29 +08:00
|
|
|
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(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-06-29 23:21:25 +08:00
|
|
|
|
2021-07-01 15:40:26 +08:00
|
|
|
pub trait ToBytes {
|
2021-07-05 16:54:41 +08:00
|
|
|
fn into_bytes(self) -> Result<Vec<u8>, String>;
|
2021-06-30 15:33:49 +08:00
|
|
|
}
|
|
|
|
|
2021-07-05 16:54:41 +08:00
|
|
|
#[cfg(feature = "use_protobuf")]
|
2021-07-03 23:14:38 +08:00
|
|
|
impl<T> ToBytes for T
|
2021-06-30 15:33:49 +08:00
|
|
|
where
|
2021-07-05 16:54:41 +08:00
|
|
|
T: std::convert::TryInto<Vec<u8>, Error = String>,
|
2021-06-30 15:33:49 +08:00
|
|
|
{
|
2021-07-05 16:54:41 +08:00
|
|
|
fn into_bytes(self) -> Result<Vec<u8>, String> { self.try_into() }
|
2021-06-30 15:33:49 +08:00
|
|
|
}
|
|
|
|
|
2021-06-30 23:11:27 +08:00
|
|
|
#[cfg(feature = "use_serde")]
|
2021-07-03 23:14:38 +08:00
|
|
|
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> {
|
2021-07-03 23:14:38 +08:00
|
|
|
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-07-03 23:14:38 +08:00
|
|
|
}
|
|
|
|
}
|
2021-06-30 23:11:27 +08:00
|
|
|
}
|