pub use distri_types::DistriConfig;
pub trait BuildHttpClient {
fn build_http_client(&self) -> Result<reqwest::Client, reqwest::Error>;
}
impl BuildHttpClient for DistriConfig {
fn build_http_client(&self) -> Result<reqwest::Client, reqwest::Error> {
let mut builder =
reqwest::Client::builder().timeout(std::time::Duration::from_secs(self.timeout_secs));
let mut headers = reqwest::header::HeaderMap::new();
if let Some(ref api_key) = self.api_key {
if api_key.starts_with("eyJ") {
if let Ok(val) =
reqwest::header::HeaderValue::from_str(&format!("Bearer {}", api_key))
{
headers.insert(reqwest::header::AUTHORIZATION, val);
}
} else {
headers.insert(
"x-api-key",
reqwest::header::HeaderValue::from_str(api_key)
.expect("Invalid API key format"),
);
}
}
if let Some(workspace_id) = &self.workspace_id {
headers.insert(
"x-workspace-id",
reqwest::header::HeaderValue::from_str(workspace_id)
.expect("Invalid workspace ID format"),
);
}
if let Some(ref traceparent) = self.traceparent
&& let Ok(val) = reqwest::header::HeaderValue::from_str(traceparent)
{
headers.insert("traceparent", val);
}
if !headers.is_empty() {
builder = builder.default_headers(headers);
}
builder.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = DistriConfig::default();
assert_eq!(config.base_url, "https://api.distri.dev/v1");
assert!(config.api_key.is_none());
assert!(!config.is_local());
}
#[test]
fn test_local_config() {
let config = DistriConfig::new("http://localhost:3033");
assert!(config.is_local());
assert!(!config.has_auth());
}
#[test]
fn test_with_api_key() {
let config = DistriConfig::default().with_api_key("test-key");
assert!(config.has_auth());
assert_eq!(config.api_key, Some("test-key".to_string()));
}
#[test]
fn test_trailing_slash_removed() {
let config = DistriConfig::new("http://localhost:3033/");
assert_eq!(config.base_url, "http://localhost:3033");
}
}