response.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. use crate::{
  2. byte_trait::FromBytes,
  3. data::Data,
  4. errors::DispatchError,
  5. request::{EventRequest, Payload},
  6. response::Responder,
  7. };
  8. use derivative::*;
  9. use std::{convert::TryFrom, fmt, fmt::Formatter};
  10. #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
  11. pub enum StatusCode {
  12. Ok = 0,
  13. Err = 1,
  14. Internal = 2,
  15. }
  16. // serde user guide: https://serde.rs/field-attrs.html
  17. #[derive(Debug, Clone, serde::Serialize, Derivative)]
  18. pub struct EventResponse {
  19. #[derivative(Debug = "ignore")]
  20. pub payload: Payload,
  21. pub status_code: StatusCode,
  22. }
  23. impl EventResponse {
  24. pub fn new(status_code: StatusCode) -> Self {
  25. EventResponse {
  26. payload: Payload::None,
  27. status_code,
  28. }
  29. }
  30. pub fn parse<T, E>(self) -> Result<Result<T, E>, DispatchError>
  31. where
  32. T: FromBytes,
  33. E: FromBytes,
  34. {
  35. match self.status_code {
  36. StatusCode::Ok => {
  37. let data = <Data<T>>::try_from(self.payload)?;
  38. Ok(Ok(data.into_inner()))
  39. },
  40. StatusCode::Err | StatusCode::Internal => {
  41. let err = <Data<E>>::try_from(self.payload)?;
  42. Ok(Err(err.into_inner()))
  43. },
  44. }
  45. }
  46. }
  47. impl std::fmt::Display for EventResponse {
  48. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  49. f.write_fmt(format_args!("Status_Code: {:?}", self.status_code))?;
  50. match &self.payload {
  51. Payload::Bytes(b) => f.write_fmt(format_args!("Data: {} bytes", b.len()))?,
  52. Payload::None => f.write_fmt(format_args!("Data: Empty"))?,
  53. }
  54. Ok(())
  55. }
  56. }
  57. impl Responder for EventResponse {
  58. #[inline]
  59. fn respond_to(self, _: &EventRequest) -> EventResponse { self }
  60. }
  61. pub type DataResult<T, E> = std::result::Result<Data<T>, E>;
  62. pub fn data_result<T, E>(data: T) -> Result<Data<T>, E>
  63. where
  64. E: Into<DispatchError>,
  65. {
  66. Ok(Data(data))
  67. }