diff --git a/src/api/client.rs b/src/api/client.rs index f11ff89..dc54847 100644 --- a/src/api/client.rs +++ b/src/api/client.rs @@ -88,8 +88,12 @@ impl ApiClient { // this will allow the user to not have to specify the auth type for each request and // xurl will be able to choose the correct auth type based on the route let token = { - let auth_ref = auth.borrow(); - auth_ref.first_oauth2_token() + let mut auth_ref = auth.borrow_mut(); + if let Some(username) = username { + auth_ref.get_token_store().get_oauth2_token(username) + } else { + auth_ref.first_oauth2_token() + } }; if let Some(token) = token { match token { @@ -117,7 +121,7 @@ impl ApiClient { } } - pub async fn build_request( +pub async fn build_request( &self, method: &str, endpoint: &str, @@ -174,20 +178,38 @@ impl ApiClient { data: Option<&str>, auth_type: Option<&str>, username: Option<&str>, + verbose: bool, ) -> Result { let request_builder = self .build_request(method, endpoint, headers, data, auth_type, username) .await?; + + let req = request_builder.try_clone().unwrap().build()?; let response = request_builder.send().await?; + if verbose { + println!("Request: {:#?}", req); + println!("Response: {:#?}", response) + } + let status = response.status(); - let body: Value = response.json().await?; - if !status.is_success() { - return Err(Error::ApiError(body)); + match response.json::().await { + Ok(res) => { + if !status.is_success() { + Err(Error::ApiError(res)) + } else { + Ok(res) + } + }, + Err(_) => { + let status = status.to_string(); + Err(Error::ApiError(serde_json::json!({ + "status": status, + "error": "Empty body" + }))) + } } - - Ok(body) } } diff --git a/src/cli.rs b/src/cli.rs index b0785a7..86f742e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -36,6 +36,10 @@ pub struct Cli { /// Username for OAuth2 authentication #[arg(short, long)] pub username: Option, + + /// Print verbose information + #[arg(short, long)] + pub verbose: bool, } #[derive(Subcommand)] diff --git a/src/main.rs b/src/main.rs index 31157dc..d131682 100644 --- a/src/main.rs +++ b/src/main.rs @@ -100,7 +100,7 @@ async fn main() -> Result<(), Error> { let client = ApiClient::new(config).with_auth(auth); // Make the request - let response = client + let response = match client .send_request( cli.method.as_deref().unwrap_or("GET"), &url, @@ -108,9 +108,27 @@ async fn main() -> Result<(), Error> { cli.data.as_deref(), cli.auth.as_deref(), cli.username.as_deref(), + cli.verbose, ) - .await?; + .await { + Ok(res) => res, + Err(e) => match e { + Error::ApiError(e) => { + println!("{}", serde_json::to_string_pretty(&e)?); + std::process::exit(1) + }, + Error::HttpError(e) => { + println!("{}", e); + std::process::exit(1) + }, + _ => { + println!("{}", e); + std::process::exit(1) + } + } + }; + // Pretty print the response println!("{}", serde_json::to_string_pretty(&response)?);