Skip to content

Commit

Permalink
refactor: refactored http calls to request fxn
Browse files Browse the repository at this point in the history
  • Loading branch information
ShubhranshuSanjeev committed May 2, 2024
1 parent aacf7e6 commit cd0ff47
Show file tree
Hide file tree
Showing 13 changed files with 282 additions and 109 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions crates/context_aware_config/src/api/context/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use diesel::{
};
use jsonschema::{Draft, JSONSchema, ValidationError};
use serde_json::{from_value, json, Map, Value};
use service_utils::helpers::validation_err_to_str;
use service_utils::service::types::DbConnection;
use service_utils::{db_error, not_found, unexpected_error, validation_error};
use std::collections::HashMap;
Expand Down Expand Up @@ -164,8 +165,8 @@ fn validate_override_with_default_configs(
let verrors = e.collect::<Vec<ValidationError>>();
log::error!("({key}) config key validation error: {:?}", verrors);
return Err(validation_error!(
"schema validation failed for {key} with error {:?}",
verrors
"schema validation failed for {key}: {}",
validation_err_to_str(verrors).first().unwrap()
));
};
}
Expand Down Expand Up @@ -522,4 +523,4 @@ async fn bulk_operations(
Ok(()) // Commit the transaction
})?;
Ok(Json(response))
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
extern crate base64;
use super::types::CreateReq;
use service_utils::helpers::validation_err_to_str;
use service_utils::{bad_argument, unexpected_error, validation_error};

use superposition_types::{SuperpositionUser, User};
Expand Down Expand Up @@ -118,9 +119,8 @@ async fn create(
verrors
);
return Err(validation_error!(
"Schema validation failed for key {} with error {:?}",
default_config.key,
verrors
"Schema validation failed: {}",
&validation_err_to_str(verrors).first().unwrap()
));
}

Expand Down Expand Up @@ -181,4 +181,4 @@ async fn get(db_conn: DbConnection) -> superposition::Result<Json<Vec<DefaultCon

let result: Vec<DefaultConfig> = default_configs.get_results(&mut conn)?;
Ok(Json(result))
}
}
24 changes: 13 additions & 11 deletions crates/context_aware_config/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};
use itertools::{self, Itertools};
use jsonschema::{Draft, JSONSchema, ValidationError};
use serde_json::{json, Value};
use service_utils::{result as superposition, validation_error};
use service_utils::{
helpers::validation_err_to_str, result as superposition, validation_error,
};
use std::collections::HashMap;

pub fn get_default_config_validation_schema() -> JSONSchema {
Expand Down Expand Up @@ -168,9 +170,9 @@ pub fn validate_context_jsonschema(
verrors
);
Err(validation_error!(
"failed to validate dimension value {:?} with error: {:?}",
dimension_value,
verrors
"failed to validate dimension value {}: {}",
dimension_value.to_string(),
validation_err_to_str(verrors).first().unwrap()
))
}
}
Expand All @@ -179,14 +181,14 @@ pub fn validate_context_jsonschema(
_ => dimension_schema.validate(dimension_value).map_err(|e| {
let verrors = e.collect::<Vec<ValidationError>>();
log::error!(
"failed to validate dimension value {:?} with error : {:?}",
dimension_value,
"failed to validate dimension value {}: {:?}",
dimension_value.to_string(),
verrors
);
validation_error!(
"failed to validate dimension value {:?} with error: {:?}",
dimension_value,
verrors
"failed to validate dimension value {}: {}",
dimension_value.to_string(),
validation_err_to_str(verrors).first().unwrap()
)
}),
}
Expand All @@ -209,8 +211,8 @@ pub fn validate_jsonschema(
//TODO: Try & render as json.
let verrors = e.collect::<Vec<ValidationError>>();
Err(validation_error!(
"schema validation failed: {:?}",
verrors.as_slice()
"schema validation failed: {}",
validation_err_to_str(verrors).first().unwrap()
))
}
};
Expand Down
3 changes: 2 additions & 1 deletion crates/frontend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ strum_macros = { workspace = true }
strum = { workspace = true }
js-sys = "0.3.65"
url = "2.5.0"
once_cell = { workspace = true }


[features]
Expand All @@ -42,4 +43,4 @@ ssr = [
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
]
]
26 changes: 10 additions & 16 deletions crates/frontend/src/components/context_form/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::types::Dimension;
use crate::utils::{get_config_value, get_host, ConfigType};
use crate::utils::{get_config_value, get_host, request, ConfigType};
use anyhow::Result;
use reqwest::StatusCode;
use serde_json::{json, Map, Value};

pub fn get_condition_schema(
Expand Down Expand Up @@ -98,21 +97,16 @@ pub async fn create_context(
overrides: Map<String, Value>,
conditions: Vec<(String, String, String)>,
dimensions: Vec<Dimension>,
) -> Result<String, String> {
let client = reqwest::Client::new();
) -> Result<serde_json::Value, String> {
let host = get_host();
let url = format!("{host}/context");
let request_payload = construct_request_payload(overrides, conditions, dimensions);
let response = client
.put(url)
.header("x-tenant", tenant)
.json(&request_payload)
.send()
.await
.map_err(|e| e.to_string())?;
match response.status() {
StatusCode::OK => response.text().await.map_err(|e| e.to_string()),
StatusCode::BAD_REQUEST => Err("Schema Validation Failed".to_string()),
_ => Err("Internal Server Error".to_string()),
}
request(
url,
reqwest::Method::PUT,
Some(request_payload),
&[("x-tenant", &tenant)],
)
.await
.map_err(|err| err.to_string())
}
31 changes: 10 additions & 21 deletions crates/frontend/src/components/default_config_form/utils.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,20 @@
use super::types::DefaultConfigCreateReq;
use crate::utils::get_host;
use reqwest::StatusCode;
use crate::utils::{get_host, request};

pub async fn create_default_config(
key: String,
tenant: String,
payload: DefaultConfigCreateReq,
) -> Result<String, String> {
let client = reqwest::Client::new();
) -> Result<serde_json::Value, String> {
let host = get_host();
let url = format!("{host}/default-config/{key}");

let response = client
.put(url)
.header("x-tenant", tenant)
.json(&payload)
.send()
.await
.map_err(|e| e.to_string())?;
match response.status() {
StatusCode::OK | StatusCode::CREATED => {
response.text().await.map_err(|e| e.to_string())
}
StatusCode::BAD_REQUEST => Err(response
.text()
.await
.unwrap_or("Validation of configuration value failed, but the error could not be understood by the system. Contact an admin for help if this persists".to_string())),
_ => Err("Internal Server Error".to_string()),
}
request(
url,
reqwest::Method::PUT,
Some(payload),
&[("x-tenant", &tenant)],
)
.await
.map_err(|err| err.to_string())
}
30 changes: 13 additions & 17 deletions crates/frontend/src/components/dimension_form/utils.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
use super::types::DimensionCreateReq;
use crate::utils::get_host;
use reqwest::StatusCode;
use crate::{
types::Dimension,
utils::{get_host, request},
};

pub async fn create_dimension(
tenant: String,
payload: DimensionCreateReq,
) -> Result<String, String> {
let client = reqwest::Client::new();
) -> Result<Dimension, String> {
let host = get_host();
let url = format!("{host}/dimension");

let response = client
.put(url)
.header("x-tenant", tenant)
.json(&payload)
.send()
.await
.map_err(|e| e.to_string())?;
match response.status() {
StatusCode::OK => response.text().await.map_err(|e| e.to_string()),
StatusCode::CREATED => response.text().await.map_err(|e| e.to_string()),
StatusCode::BAD_REQUEST => Err("Schema Validation Failed".to_string()),
_ => Err("Internal Server Error".to_string()),
}
request(
url,
reqwest::Method::PUT,
Some(payload),
&[("x-tenant", &tenant)],
)
.await
.map_err(|err| err.to_string())
}
54 changes: 20 additions & 34 deletions crates/frontend/src/components/experiment_form/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ use super::types::{
};
use crate::components::context_form::utils::construct_context;
use crate::types::{Dimension, Variant};
use crate::utils::get_host;
use reqwest::StatusCode;
use serde_json::json;
use crate::utils::{get_host, request};
use serde_json::Value;

pub fn validate_experiment(experiment: &ExperimentCreateRequest) -> Result<bool, String> {
if experiment.name.is_empty() {
Expand All @@ -20,7 +19,7 @@ pub async fn create_experiment(
name: String,
tenant: String,
dimensions: Vec<Dimension>,
) -> Result<String, String> {
) -> Result<Value, String> {
let payload = ExperimentCreateRequest {
name,
variants,
Expand All @@ -29,29 +28,23 @@ pub async fn create_experiment(

let _ = validate_experiment(&payload)?;

let client = reqwest::Client::new();
let host = get_host();
let url = format!("{host}/experiments");
let request_payload = json!(payload);
let response = client
.post(url)
.header("x-tenant", tenant)
.json(&request_payload)
.send()
.await
.map_err(|e| e.to_string())?;
match response.status() {
StatusCode::OK => response.text().await.map_err(|e| e.to_string()),
StatusCode::BAD_REQUEST => Err("epxeriment data corrupt".to_string()),
_ => Err("Internal Server Error".to_string()),
}
request(
url,
reqwest::Method::POST,
Some(payload),
&[("x-tenant", &tenant)],
)
.await
.map_err(|err| err.to_string())
}

pub async fn update_experiment(
experiment_id: String,
variants: Vec<Variant>,
tenant: String,
) -> Result<String, String> {
) -> Result<Value, String> {
let payload = ExperimentUpdateRequest {
variants: variants
.into_iter()
Expand All @@ -62,22 +55,15 @@ pub async fn update_experiment(
.collect::<Vec<VariantUpdateRequest>>(),
};

let client = reqwest::Client::new();
let host = get_host();
let url = format!("{}/experiments/{}/overrides", host, experiment_id);
let request_payload = json!(payload);
let response = client
.put(url)
.header("x-tenant", tenant)
.header("Authorization", "Bearer 12345678")
.json(&request_payload)
.send()
.await
.map_err(|e| e.to_string())?;

match response.status() {
StatusCode::OK => response.text().await.map_err(|e| e.to_string()),
StatusCode::BAD_REQUEST => Err("epxeriment data corrupt".to_string()),
_ => Err("Internal Server Error".to_string()),
}
request(
url,
reqwest::Method::PUT,
Some(payload),
&[("x-tenant", &tenant)],
)
.await
.map_err(|err| err.to_string())
}
2 changes: 1 addition & 1 deletion crates/frontend/src/providers/alert_provider/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::time::Duration;

use leptos::*;

use crate::components::toast::{Alert, AlertType};
use crate::components::alert::{Alert, AlertType};

#[derive(Clone, Debug)]
pub struct AlertQueue {
Expand Down
7 changes: 7 additions & 0 deletions crates/frontend/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,10 @@ pub struct BreadCrums {
pub value: Option<String>,
pub is_link: bool,
}

/************************************************************************/

#[derive(Debug, Clone, Deserialize)]
pub struct ErrorResponse {
pub message: String,
}
Loading

0 comments on commit cd0ff47

Please sign in to comment.