Skip to content

Commit

Permalink
made service.rs class
Browse files Browse the repository at this point in the history
  • Loading branch information
aaravm committed Jun 9, 2024
1 parent 4210498 commit 61fcb7a
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 35 deletions.
105 changes: 73 additions & 32 deletions lib/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ use serde::Serialize;
use serde_json::Value;
use std::error::Error;


use crate::{tes::ResponseContent, tes::models};

pub enum CreateTaskError {
UnknownValue(serde_json::Value),
}

#[derive(Debug)]
pub struct Service {
base_url: String,
Expand Down Expand Up @@ -30,48 +37,82 @@ impl Service {
data: Option<Value>,
params: Option<Value>,
) -> Result<Value, Box<dyn Error>> {
let url = format!("{}/{}", self.base_url, endpoint);
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("Content-Type", "application/json".parse()?);

if let Some(token) = &self.token {
headers.insert(
"Authorization",
format!("Bearer {}", token).parse()?,
);
}
// What client are we using?
let mut local_var_req_builder = self.client.request(reqwest::Method::POST, endpoint);

let mut req_builder = self.client.request(method, &url).headers(headers);

if let Some(data) = data {
req_builder = req_builder.json(&data);
if let Some(ref local_var_user_agent) = self.username {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}

// Check what are data and params
local_var_req_builder = local_var_req_builder.json(&data);

if let Some(params) = params {
req_builder = req_builder.query(&params);
}
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = self.client.execute(local_var_req).await?;

let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;

let response = req_builder.send().await?;

if !response.status().is_success() {
let error_message = format!("Error: HTTP {} - {}", response.status(), response.status().canonical_reason().unwrap_or("Unknown error"));
// Check what to return, whether Result<Value, Box<dyn Error>> or not
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(|e| Box::new(e) as Box<dyn Error>)
// serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
// let local_var_entity: Option<CreateTaskError> = serde_json::from_str(&local_var_content).ok();
// let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
// Err(Error::ResponseError(local_var_error))
let error_message = format!("Error: HTTP {} - {}", local_var_status, local_var_status.canonical_reason().unwrap_or("Unknown error"));
eprintln!("{}", error_message);
return Err(error_message.into());
Err(error_message.into())
}

let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("");
//GA4GH-CLI PYTHON CODE CONVERTED TO RUST (OLD CODE)

let response_data = if content_type.contains("application/json") {
response.json::<Value>().await?
} else {
Value::String(response.text().await?)
};

// let url = format!("{}/{}", self.base_url, endpoint);
// let mut headers = reqwest::header::HeaderMap::new();
// headers.insert("Content-Type", "application/json".parse()?);

Ok(response_data)
// if let Some(token) = &self.token {
// headers.insert(
// "Authorization",
// format!("Bearer {}", token).parse()?,
// );
// }

// let mut req_builder = self.client.request(method, &url).headers(headers);

// if let Some(data) = data {
// req_builder = req_builder.json(&data);
// }

// if let Some(params) = params {
// req_builder = req_builder.query(&params);
// }

// let response = req_builder.send().await?;

// if !response.status().is_success() {
// let error_message = format!("Error: HTTP {} - {}", response.status(), response.status().canonical_reason().unwrap_or("Unknown error"));
// eprintln!("{}", error_message);
// return Err(error_message.into());
// }

// let content_type = response
// .headers()
// .get(reqwest::header::CONTENT_TYPE)
// .and_then(|value| value.to_str().ok())
// .unwrap_or("");

// let response_data = if content_type.contains("application/json") {
// response.json::<Value>().await?
// } else {
// Value::String(response.text().await?)
// };

// Ok(response_data)
}

}

6 changes: 3 additions & 3 deletions lib/src/tes/tes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ pub async fn create_task(configuration: &configuration::Configuration, params: C

// unbox the parameters
let body = params.body;



let local_var_client = &local_var_configuration.client;

let local_var_uri_str = format!("{}/tasks", local_var_configuration.base_path);
let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());
let endpoint = local_var_uri_str.as_str();
let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, endpoint);

if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
Expand Down

1 comment on commit 61fcb7a

@pavelnikonorov
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. TES could also be a struct/trait, like Service;
  2. TES could use request fn of Service instead of working with reqwest directly;
  3. you might look at Rust’s Deref and DerefMut standard traits to achieve a more seamless inheritance-like behaviour If you want TES to directly inherit the request function from Service;
  4. consider name convention optimising for local variables, "local_" can be removed.

Please sign in to comment.