#![warn(clippy::pedantic)]
#![warn(deprecated_in_future)]
#![warn(future_incompatible)]
#![warn(unreachable_pub)]
#![warn(missing_debug_implementations)]
#![warn(rust_2018_compatibility)]
#![warn(rust_2018_idioms)]
#![warn(unused)]
#![deny(warnings)]
#![doc(html_root_url = "https://docs.rs/reqwest-pretty-json/0.10.0")]
use serde::Serialize;
use serde_json::to_vec_pretty;
pub trait PrettyJson<T>: Sized
where
T: Serialize + ?Sized,
{
fn pretty_json(self, json: &T) -> Self;
}
impl<T> PrettyJson<T> for reqwest::RequestBuilder
where
T: Serialize + ?Sized,
{
fn pretty_json(self, json: &T) -> Self {
let builder = self.json(json);
match to_vec_pretty(json) {
Ok(body) => builder.body(body),
Err(_) => builder,
}
}
}
impl<T> PrettyJson<T> for reqwest::blocking::RequestBuilder
where
T: Serialize + ?Sized,
{
fn pretty_json(self, json: &T) -> Self {
let builder = self.json(json);
match to_vec_pretty(json) {
Ok(body) => builder.body(body),
Err(_) => builder,
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::error::Error;
use reqwest::StatusCode;
use serde_json::{to_string, to_string_pretty, to_value, Value};
use super::*;
#[tokio::test]
async fn pretty_json_async() -> Result<(), Box<dyn Error>> {
let mut data = HashMap::<_, Vec<u8>>::new();
data.insert("foo", vec![1, 2, 3]);
let body_should_be = to_string_pretty(&data)?;
let body_shouldnt_be = to_string(&data)?;
let value = to_value(&data)?;
let client = reqwest::Client::new();
let response = client
.post("http://httpbin.org/post")
.pretty_json(&data)
.send()
.await?;
assert_eq!(response.status(), StatusCode::OK);
let result: Value = response.json().await?;
assert_eq!(result["data"], body_should_be);
assert_ne!(result["data"], body_shouldnt_be);
assert_eq!(result["headers"]["Content-Type"], "application/json");
assert_eq!(result["json"], value);
Ok(())
}
#[test]
fn pretty_json_blocking() -> Result<(), Box<dyn Error>> {
let mut data = HashMap::new();
data.insert("foo", vec![1, 2, 3]);
let body_should_be = to_string_pretty(&data)?;
let body_shouldnt_be = to_string(&data)?;
let value = to_value(&data)?;
let client = reqwest::blocking::Client::new();
let response = client
.post("http://httpbin.org/post")
.pretty_json(&data)
.send()?;
assert_eq!(response.status(), StatusCode::OK);
let result: Value = response.json().unwrap();
assert_eq!(result["data"], body_should_be);
assert_ne!(result["data"], body_shouldnt_be);
assert_eq!(result["headers"]["Content-Type"], "application/json");
assert_eq!(result["json"], value);
Ok(())
}
}