msg.rs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use serde::{Deserialize, Serialize};
  2. use serde_repr::*;
  3. use tokio_tungstenite::tungstenite::Message as TokioMessage;
  4. #[derive(Serialize, Deserialize, Debug, Clone, Default)]
  5. pub struct WebSocketRawMessage {
  6. pub channel: WSChannel,
  7. pub data: Vec<u8>,
  8. }
  9. impl WebSocketRawMessage {
  10. pub fn to_bytes(&self) -> Vec<u8> {
  11. serde_json::to_vec(&self).unwrap_or_default()
  12. }
  13. pub fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Self {
  14. serde_json::from_slice(bytes.as_ref()).unwrap_or_default()
  15. }
  16. }
  17. // The lib-ws crate should not contain business logic.So WSChannel should be removed into another place.
  18. #[derive(Serialize_repr, Deserialize_repr, Debug, Clone, Eq, PartialEq, Hash)]
  19. #[repr(u8)]
  20. #[derive(Default)]
  21. pub enum WSChannel {
  22. #[default]
  23. Document = 0,
  24. Folder = 1,
  25. Database = 2,
  26. }
  27. impl ToString for WSChannel {
  28. fn to_string(&self) -> String {
  29. match self {
  30. WSChannel::Document => "0".to_string(),
  31. WSChannel::Folder => "1".to_string(),
  32. WSChannel::Database => "2".to_string(),
  33. }
  34. }
  35. }
  36. impl std::convert::From<WebSocketRawMessage> for TokioMessage {
  37. fn from(msg: WebSocketRawMessage) -> Self {
  38. TokioMessage::Binary(msg.to_bytes())
  39. }
  40. }