response.rs 2.0 KB

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