smarty_rust_sdk/sdk/
client.rs1use 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
10pub(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 builder = builder.query(&[("license".to_string(), self.options.license.clone())]);
59
60 for (header_key, header_value) in self.options.headers.clone() {
61 builder = builder.header(header_key, header_value);
62 }
63
64 builder = builder.header(
65 USER_AGENT.to_string(),
66 format!("smarty (sdk:rust@{})", VERSION),
67 );
68
69 builder
70 }
71}