1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! WebSocket message types
use serde::{Deserialize, Serialize};
/// Message type
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageType {
Text,
Binary,
Ping,
Pong,
Close,
}
/// WebSocket message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebSocketMessage {
pub message_type: MessageType,
pub data: serde_json::Value,
pub timestamp: Option<i64>,
}
impl WebSocketMessage {
/// Creates a new text message with the given JSON data.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::message::WebSocketMessage;
/// use serde_json::json;
///
/// let msg = WebSocketMessage::text(json!({"hello": "world"}));
/// assert!(matches!(msg.message_type, reinhardt_websockets::message::MessageType::Text));
/// assert_eq!(msg.data, json!({"hello": "world"}));
/// assert!(msg.timestamp.is_none());
/// ```
pub fn text(data: serde_json::Value) -> Self {
Self {
message_type: MessageType::Text,
data,
timestamp: None,
}
}
/// Creates a new binary message with the given JSON data.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::message::WebSocketMessage;
/// use serde_json::json;
///
/// let msg = WebSocketMessage::binary(json!([1, 2, 3, 4]));
/// assert!(matches!(msg.message_type, reinhardt_websockets::message::MessageType::Binary));
/// assert_eq!(msg.data, json!([1, 2, 3, 4]));
/// assert!(msg.timestamp.is_none());
/// ```
pub fn binary(data: serde_json::Value) -> Self {
Self {
message_type: MessageType::Binary,
data,
timestamp: None,
}
}
/// Adds a timestamp to the message representing the current time.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::message::WebSocketMessage;
/// use serde_json::json;
///
/// let msg = WebSocketMessage::text(json!({"hello": "world"}))
/// .with_timestamp();
/// assert!(msg.timestamp.is_some());
/// assert!(msg.timestamp.unwrap() > 0);
/// ```
pub fn with_timestamp(mut self) -> Self {
self.timestamp = Some(chrono::Utc::now().timestamp());
self
}
}