lattice_sdk/
client.rs

1use crate::api::resources::LatticeClient;
2use crate::{ApiError, ClientConfig};
3use std::collections::HashMap;
4use std::time::Duration;
5
6/*
7Things to know:
8
9`impl Into<String>` is a generic parameter constraint in Rust that means "accept any type that can be converted into a String."
10It's essentially Rust's way of saying "I'll take a string in any form you give it to me."
11
12Types that implement Into<String>:
13
14// All of these work:
15builder.api_key("hello")           // &str
16builder.api_key("hello".to_string()) // String
17builder.api_key(format!("key_{}", id)) // String from format!
18builder.api_key(my_string_variable)    // String variable
19*/
20
21/// Builder for creating API clients with custom configuration
22pub struct ApiClientBuilder {
23    config: ClientConfig,
24}
25
26impl ApiClientBuilder {
27    /// Create a new builder with the specified base URL
28    pub fn new(base_url: impl Into<String>) -> Self {
29        let mut config = ClientConfig::default();
30        config.base_url = base_url.into();
31        Self { config }
32    }
33
34    /// Set the API key for authentication
35    pub fn api_key(mut self, key: impl Into<String>) -> Self {
36        self.config.api_key = Some(key.into());
37        self
38    }
39
40    /// Set the bearer token for authentication
41    pub fn token(mut self, token: impl Into<String>) -> Self {
42        self.config.token = Some(token.into());
43        self
44    }
45
46    /// Set the username for basic authentication
47    pub fn username(mut self, username: impl Into<String>) -> Self {
48        self.config.username = Some(username.into());
49        self
50    }
51
52    /// Set the password for basic authentication
53    pub fn password(mut self, password: impl Into<String>) -> Self {
54        self.config.password = Some(password.into());
55        self
56    }
57
58    /// Set the request timeout
59    pub fn timeout(mut self, timeout: Duration) -> Self {
60        self.config.timeout = timeout;
61        self
62    }
63
64    /// Set the maximum number of retries
65    pub fn max_retries(mut self, retries: u32) -> Self {
66        self.config.max_retries = retries;
67        self
68    }
69
70    /// Add a custom header
71    pub fn custom_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
72        self.config.custom_headers.insert(key.into(), value.into());
73        self
74    }
75
76    /// Add multiple custom headers
77    pub fn custom_headers(mut self, headers: HashMap<String, String>) -> Self {
78        self.config.custom_headers.extend(headers);
79        self
80    }
81
82    /// Set the user agent
83    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
84        self.config.user_agent = user_agent.into();
85        self
86    }
87
88    /// Build the client with validation
89    pub fn build(self) -> Result<LatticeClient, ApiError> {
90        LatticeClient::new(self.config)
91    }
92}