fiberplane_api_client/
builder.rs

1use crate::api_client::ApiClient;
2use anyhow::Result;
3use reqwest::{header, Url};
4use std::time::Duration;
5
6#[derive(Debug)]
7pub struct ApiClientBuilder {
8    // Some client specific values
9    base_url: Url,
10    timeout: Option<Duration>,
11
12    // These values will be mapped to header values
13    user_agent: Option<String>,
14    bearer_token: Option<String>,
15}
16
17impl ApiClientBuilder {
18    pub fn new(base_url: Url) -> Self {
19        Self {
20            base_url,
21            timeout: None,
22            user_agent: None,
23            bearer_token: None,
24        }
25    }
26
27    /// Override the base_url for the ApiClient.
28    pub fn base_url(mut self, base_url: Url) -> Self {
29        self.base_url = base_url;
30        self
31    }
32
33    /// Change the timeout for the ApiClient.
34    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
35        self.timeout = timeout;
36        self
37    }
38
39    /// Override the user agent for the ApiClient.
40    pub fn user_agent(mut self, user_agent: Option<impl Into<String>>) -> Self {
41        self.user_agent = user_agent.map(|agent| agent.into());
42        self
43    }
44
45    /// Set an authentication token for the ApiClient.
46    pub fn bearer_token(mut self, bearer_token: Option<impl Into<String>>) -> Self {
47        self.bearer_token = bearer_token.map(|token| token.into());
48        self
49    }
50
51    pub fn build_client(&self) -> Result<reqwest::Client> {
52        let mut headers = header::HeaderMap::new();
53
54        headers.insert(
55            header::USER_AGENT,
56            header::HeaderValue::from_str(
57                self.user_agent
58                    .as_deref()
59                    .unwrap_or("Fiberplane Rust API client"),
60            )?,
61        );
62
63        if let Some(bearer) = &self.bearer_token {
64            headers.insert(
65                header::AUTHORIZATION,
66                header::HeaderValue::from_str(&format!("Bearer {}", bearer))?,
67            );
68        }
69
70        let client = reqwest::Client::builder()
71            .connect_timeout(self.timeout.unwrap_or_else(|| Duration::from_secs(5)))
72            .default_headers(headers)
73            .build()?;
74
75        Ok(client)
76    }
77
78    /// Build the ApiClient.
79    pub fn build(self) -> Result<ApiClient> {
80        let client = self.build_client()?;
81        let server = self.base_url;
82        Ok(ApiClient { client, server })
83    }
84}