use serde::Serialize;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RequestBody {
None,
String(String),
Json(serde_json::Value),
Xml(String), }
impl Default for RequestBody {
fn default() -> Self {
Self::None
}
}
impl TryFrom<&RequestBody> for String {
type Error = serde_json::Error;
fn try_from(value: &RequestBody) -> Result<Self, Self::Error> {
match value {
RequestBody::None => Ok("".to_string()),
RequestBody::String(s) => Ok(s.to_string()),
RequestBody::Json(json) => serde_json::to_string(&json),
RequestBody::Xml(s) => Ok(s.to_string()),
}
}
}
impl RequestBody {
pub fn json<T: Serialize>(source: T) -> Result<Self, serde_json::Error> {
serde_json::to_value(source).map(Self::Json)
}
pub fn content_type(&self) -> Option<String> {
match self {
Self::None => None,
Self::String(_) => Some("text/plain".to_string()),
Self::Json(_) => Some("application/json".to_string()),
Self::Xml(_) => Some("application/xml".to_string()),
}
}
}
#[cfg(test)]
mod tests {
use assert2::let_assert;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
#[test_log::test]
fn test_request_body_json() {
let_assert!(Ok(json) = RequestBody::json("hello"));
assert_eq!(
json,
RequestBody::Json(serde_json::Value::String("hello".to_string()))
);
}
#[test_log::test]
fn test_request_body_content_type() {
assert_eq!(RequestBody::None.content_type(), None);
assert_eq!(
RequestBody::String("".to_string()).content_type(),
Some("text/plain".to_string())
);
assert_eq!(
RequestBody::Json(json!("")).content_type(),
Some("application/json".to_string())
);
assert_eq!(
RequestBody::Xml("".to_string()).content_type(),
Some("application/xml".to_string())
);
}
#[test_log::test]
fn test_request_body_try_from() {
let_assert!(Ok(value) = String::try_from(&RequestBody::None));
assert_eq!(value, "");
let_assert!(Ok(value) = String::try_from(&RequestBody::String("hello".to_string())));
assert_eq!(value, "hello");
let_assert!(Ok(value) = String::try_from(&RequestBody::Json(json!("hello"))));
assert_eq!(value, "\"hello\"");
let_assert!(Ok(value) = String::try_from(&RequestBody::Xml("hello".to_string())));
assert_eq!(value, "hello");
}
}