Skip to main content

camel_api/
body.rs

1use bytes::Bytes;
2
3/// The body of a message, supporting common payload types.
4#[derive(Debug, Clone, Default)]
5pub enum Body {
6    /// No body content.
7    #[default]
8    Empty,
9    /// Raw bytes payload.
10    Bytes(Bytes),
11    /// UTF-8 string payload.
12    Text(String),
13    /// JSON payload.
14    Json(serde_json::Value),
15}
16
17impl Body {
18    /// Returns `true` if the body is empty.
19    pub fn is_empty(&self) -> bool {
20        matches!(self, Body::Empty)
21    }
22
23    /// Try to get the body as a string, converting from bytes if needed.
24    pub fn as_text(&self) -> Option<&str> {
25        match self {
26            Body::Text(s) => Some(s.as_str()),
27            _ => None,
28        }
29    }
30}
31
32// Conversion impls
33impl From<String> for Body {
34    fn from(s: String) -> Self {
35        Body::Text(s)
36    }
37}
38
39impl From<&str> for Body {
40    fn from(s: &str) -> Self {
41        Body::Text(s.to_string())
42    }
43}
44
45impl From<Bytes> for Body {
46    fn from(b: Bytes) -> Self {
47        Body::Bytes(b)
48    }
49}
50
51impl From<Vec<u8>> for Body {
52    fn from(v: Vec<u8>) -> Self {
53        Body::Bytes(Bytes::from(v))
54    }
55}
56
57impl From<serde_json::Value> for Body {
58    fn from(v: serde_json::Value) -> Self {
59        Body::Json(v)
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn test_body_default_is_empty() {
69        let body = Body::default();
70        assert!(body.is_empty());
71    }
72
73    #[test]
74    fn test_body_from_string() {
75        let body = Body::from("hello".to_string());
76        assert_eq!(body.as_text(), Some("hello"));
77    }
78
79    #[test]
80    fn test_body_from_str() {
81        let body = Body::from("world");
82        assert_eq!(body.as_text(), Some("world"));
83    }
84
85    #[test]
86    fn test_body_from_bytes() {
87        let body = Body::from(Bytes::from_static(b"data"));
88        assert!(!body.is_empty());
89        assert!(matches!(body, Body::Bytes(_)));
90    }
91
92    #[test]
93    fn test_body_from_json() {
94        let val = serde_json::json!({"key": "value"});
95        let body = Body::from(val.clone());
96        assert!(matches!(body, Body::Json(_)));
97    }
98}