BodyData

Enum BodyData 

Source
pub enum BodyData {
    ValidJson(Value),
    RawString(String),
}
Expand description

Flexible representation of message body content supporting both JSON and raw text.

This enum handles the diverse nature of Service Bus message content, providing type-safe handling for both structured JSON data and plain text messages. The parser attempts JSON deserialization first, falling back to raw string storage to ensure no message content is lost.

§Variants

  • ValidJson - Successfully parsed JSON content stored as serde_json::Value
  • RawString - Plain text or unparseable content stored as UTF-8 string

§Examples

§Working with JSON Messages

use quetty_server::model::BodyData;
use serde_json::{json, Value};

// Create JSON message body
let json_body = BodyData::ValidJson(json!({
    "orderId": 12345,
    "customerId": "customer-001",
    "items": [
        {"productId": "prod-001", "quantity": 2},
        {"productId": "prod-002", "quantity": 1}
    ],
    "total": 149.99
}));

// Access JSON content
if let BodyData::ValidJson(value) = &json_body {
    if let Some(order_id) = value.get("orderId").and_then(|v| v.as_i64()) {
        println!("Processing order: {}", order_id);
    }

    if let Some(items) = value.get("items").and_then(|v| v.as_array()) {
        println!("Order contains {} items", items.len());
    }
}

§Working with Text Messages

use quetty_server::model::BodyData;

// Create text message body
let text_body = BodyData::RawString("Hello, Service Bus!".to_string());

// Access text content
if let BodyData::RawString(content) = &text_body {
    println!("Message content: {}", content);

    // Process text content
    let word_count = content.split_whitespace().count();
    println!("Message contains {} words", word_count);
}

§Pattern Matching for Different Content Types

use quetty_server::model::{BodyData, MessageModel};
use serde_json::Value;

fn process_message(message: &MessageModel) {
    match &message.body {
        BodyData::ValidJson(json_value) => {
            println!("Processing JSON message");

            // Handle different JSON message types
            match json_value.get("type").and_then(|v| v.as_str()) {
                Some("order") => process_order_message(json_value),
                Some("notification") => process_notification_message(json_value),
                Some("event") => process_event_message(json_value),
                _ => println!("Unknown JSON message type"),
            }
        }
        BodyData::RawString(text) => {
            println!("Processing text message: {}", text);

            // Handle different text formats
            if text.starts_with("CMD:") {
                process_command_message(text);
            } else if text.contains("ERROR") {
                process_error_message(text);
            } else {
                process_plain_text_message(text);
            }
        }
    }
}

§Serialization Behavior

use quetty_server::model::BodyData;
use serde_json::{json, to_string};

// JSON bodies serialize as their JSON content
let json_body = BodyData::ValidJson(json!({"key": "value"}));
let json_serialized = to_string(&json_body)?;
assert_eq!(json_serialized, r#"{"key":"value"}"#);

// Text bodies serialize as quoted strings
let text_body = BodyData::RawString("Hello, World!".to_string());
let text_serialized = to_string(&text_body)?;
assert_eq!(text_serialized, r#""Hello, World!""#);

§Content Type Detection

use quetty_server::model::BodyData;

fn analyze_message_content(body: &BodyData) -> String {
    match body {
        BodyData::ValidJson(value) => {
            format!("JSON message with {} top-level fields",
                    value.as_object().map(|o| o.len()).unwrap_or(0))
        }
        BodyData::RawString(text) => {
            let char_count = text.chars().count();
            let line_count = text.lines().count();
            format!("Text message: {} characters, {} lines", char_count, line_count)
        }
    }
}

§Creating from Raw Data

use quetty_server::model::BodyData;
use serde_json::{from_str, Value};

fn create_body_from_bytes(data: &[u8]) -> BodyData {
    // Try to parse as UTF-8 first
    match std::str::from_utf8(data) {
        Ok(text) => {
            // Try to parse as JSON
            match from_str::<Value>(text) {
                Ok(json) => BodyData::ValidJson(json),
                Err(_) => BodyData::RawString(text.to_string()),
            }
        }
        Err(_) => {
            // Fallback to lossy UTF-8 conversion for binary data
            BodyData::RawString(String::from_utf8_lossy(data).into_owned())
        }
    }
}

§Performance Notes

  • JSON parsing is performed only once during message conversion
  • Value type provides efficient access to JSON structure without re-parsing
  • String storage uses Rust’s efficient string handling
  • Cloning is optimized through reference counting for large JSON objects

§Thread Safety

BodyData implements Clone, Send, and Sync, making it safe for concurrent use across threads and async tasks.

Variants§

§

ValidJson(Value)

Successfully parsed JSON content.

Contains a serde_json::Value that provides structured access to the JSON data. This allows for efficient querying and manipulation of JSON message content.

§

RawString(String)

Raw text content that couldn’t be parsed as JSON.

Contains the original message content as a UTF-8 string. This preserves all message data even for non-JSON content or malformed JSON that couldn’t be parsed.

Trait Implementations§

Source§

impl Clone for BodyData

Source§

fn clone(&self) -> BodyData

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BodyData

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for BodyData

Source§

fn eq(&self, other: &BodyData) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for BodyData

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for BodyData

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> SendBound for T
where T: Send,