smarty_rust_sdk/sdk/
client.rs

1use crate::sdk::logging::LoggingMiddleware;
2use crate::sdk::options::Options;
3use crate::sdk::VERSION;
4use reqwest::header::USER_AGENT;
5use reqwest_middleware::{ClientBuilder, ClientWithMiddleware, RequestBuilder};
6use url::Url;
7
8use super::{error::SmartyError, retry_strategy::SmartyRetryMiddleware};
9
10/// The base client for all of Smarty's rust sdk
11pub(crate) struct Client {
12    pub(crate) reqwest_client: ClientWithMiddleware,
13    pub(crate) url: Url,
14    pub(crate) options: Options,
15}
16
17impl Client {
18    pub(crate) fn new(
19        base_url: Url,
20        options: Options,
21        api_path: &str,
22    ) -> Result<Client, SmartyError> {
23        let url = &mut base_url.join(api_path)?;
24
25        let mut reqwest_client_builder = reqwest::ClientBuilder::new();
26
27        if let Some(proxy) = options.proxy.clone() {
28            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
29        }
30
31        let mut client_builder = ClientBuilder::new(
32            reqwest_client_builder
33                .build()
34                .map_err(SmartyError::RequestProcess)?,
35        )
36        .with(SmartyRetryMiddleware::new(options.num_retries));
37
38        if options.logging_enabled {
39            client_builder = client_builder.with(LoggingMiddleware);
40        }
41
42        let client = client_builder.build();
43
44        let client = Client {
45            reqwest_client: client,
46            url: url.clone(),
47            options,
48        };
49
50        Ok(client)
51    }
52
53    pub(crate) fn build_request(&self, mut builder: RequestBuilder) -> RequestBuilder {
54        if let Some(auth) = &self.options.authentication {
55            builder = auth.authenticate(builder);
56        }
57        
58        if !self.options.license.is_empty() {
59            builder = builder.query(&[("license".to_string(), self.options.license.clone())]);   
60        }
61
62        for (header_key, header_value) in self.options.headers.clone() {
63            builder = builder.header(header_key, header_value);
64        }
65
66        builder = builder.header(
67            USER_AGENT.to_string(),
68            format!("smarty (sdk:rust@{})", VERSION),
69        );
70
71        builder
72    }
73}