Skip to main content

arazzo_models/
payloads.rs

1//! Structs and Traits for dealing with body payloads
2
3use std::any::Any;
4use std::fmt::Debug;
5
6use bytes::Bytes;
7use serde_json::Value;
8
9/// Body Payload
10pub trait Payload: Debug + Any {
11  /// Returns the raw bytes of the payload. Note that in some cases this will return a new copy
12  /// of the payload bytes.
13  fn as_bytes(&self) -> Bytes;
14
15  /// Returns the payload as a String.
16  fn as_string(&self) -> String;
17
18  /// Returns the payload as a JSON document if it is easily convertable, otherwise returns None.
19  fn as_json(&self) -> Option<Value> {
20    None
21  }
22}
23
24/// Payload stored as a String value
25#[derive(Clone, Debug)]
26pub struct StringPayload(pub String);
27
28impl Payload for StringPayload {
29  fn as_bytes(&self) -> Bytes {
30    Bytes::from(self.0.clone())
31  }
32
33  fn as_string(&self) -> String {
34    self.0.clone()
35  }
36}
37
38/// Empty Payload
39#[derive(Clone, Debug)]
40pub struct EmptyPayload;
41
42impl Payload for EmptyPayload {
43  fn as_bytes(&self) -> Bytes {
44    Bytes::new()
45  }
46
47  fn as_string(&self) -> String {
48    String::new()
49  }
50}
51
52/// Payload stored as a JSON document. Note that this does not mean a JSON payload (that would be
53/// depending on the content type), but that the source of the payload is stored as JSON.
54#[derive(Clone, Debug)]
55pub struct JsonPayload(pub Value);
56
57impl Payload for JsonPayload {
58  fn as_bytes(&self) -> Bytes {
59    Bytes::from(self.0.to_string())
60  }
61
62  fn as_string(&self) -> String {
63    self.0.to_string()
64  }
65
66  fn as_json(&self) -> Option<Value> {
67    Some(self.0.clone())
68  }
69}