Skip to content

Commit

Permalink
🚸 Prettify JSON response body (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
bayne authored Jan 26, 2020
1 parent cf0629a commit ff7b4a8
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 7 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ branches:
only:
# release tags
- /^v\d+\.\d+\.\d+.*$/
- master

notifications:
email:
Expand Down
1 change: 0 additions & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ branches:
only:
# Release tags
- /^v\d+\.\d+\.\d+.*$/
- master

notifications:
- provider: Email
Expand Down
21 changes: 17 additions & 4 deletions src/response_handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,26 @@ impl DefaultOutputter {
}
}

fn prettify_response_body(body: &str) -> String {
match serde_json::from_str(body) {
Ok(serde_json::Value::Object(response_body)) => {
serde_json::to_string_pretty(&response_body).unwrap()
}
_ => String::from(body),
}
}

impl Outputter for DefaultOutputter {
type Response = DefaultResponse;

fn output_response(&mut self, response: &Self::Response) -> Result<(), Error> {
println!("{}", response);

let DefaultResponse(Response { body, .. }) = response;

let body = prettify_response_body(body.as_str());
println!("\n{}", body);

Ok(())
}

Expand Down Expand Up @@ -153,12 +168,10 @@ impl Display for DefaultResponse {
.collect();
formatter.write_fmt(format_args!(
"{http_version} {status}\
{headers}
{body}",
{headers}",
http_version = response.version,
status = response.status,
headers = headers,
body = format!("\n{}", response.body),
headers = headers
))
}
}
Expand Down
22 changes: 21 additions & 1 deletion src/response_handler/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::model::{Response, Version};
use crate::response_handler::boa::DefaultResponseHandler;
use crate::response_handler::{DefaultResponse, ResponseHandler, ScriptResponse};
use crate::response_handler::{
prettify_response_body, DefaultResponse, ResponseHandler, ScriptResponse,
};
use crate::script_engine::boa::BoaScriptEngine;
use crate::script_engine::{Script, ScriptEngine};
use serde_json::{Map, Value};
Expand Down Expand Up @@ -39,6 +41,24 @@ fn test_headers_available_in_response() {
assert_eq!("SomeTokenValue", result);
}

#[test]
fn test_output_is_prettified() {
let pretty_body = prettify_response_body("simple");

assert_eq!("simple", pretty_body);

let pretty_body = prettify_response_body("{\"stuff\": \"andThings\"}");

assert_eq!(
"\
{
\"stuff\": \"andThings\"
}\
",
pretty_body
);
}

#[test]
fn test_headers_for_script_response() {
let response = DefaultResponse(Response {
Expand Down

0 comments on commit ff7b4a8

Please sign in to comment.