clientix_core/client/asynchronous/
client.rs

1use std::sync::{Arc, Mutex};
2use http::Method;
3use reqwest::Client as ReqwestClient;
4use crate::client::asynchronous::request::AsyncRequest;
5use crate::client::ClientConfig;
6
7#[derive(Clone)]
8pub struct AsyncClient {
9    pub client: Arc<Mutex<ReqwestClient>>,
10    pub url: String,
11    pub path: String
12}
13
14impl AsyncClient {
15
16    pub fn get(&self) -> AsyncRequest {
17        AsyncRequest::builder(self.clone(), Method::GET)
18    }
19
20    pub fn post(&self) -> AsyncRequest {
21        AsyncRequest::builder(self.clone(), Method::POST)
22    }
23
24    pub fn put(&self) -> AsyncRequest {
25        AsyncRequest::builder(self.clone(), Method::PUT)
26    }
27
28    pub fn delete(&self) -> AsyncRequest {
29        AsyncRequest::builder(self.clone(), Method::DELETE)
30    }
31    
32    pub fn head(&self) -> AsyncRequest {
33        AsyncRequest::builder(self.clone(), Method::HEAD)
34    }
35    
36    pub fn patch(&self) -> AsyncRequest {
37        AsyncRequest::builder(self.clone(), Method::PATCH)
38    }
39
40}
41
42impl From<ClientConfig> for AsyncClient {
43
44    fn from(config: ClientConfig) -> Self {
45        let mut client = ReqwestClient::builder();
46
47        if let Some(user_agent) = config.user_agent {
48            client = client.user_agent(user_agent.clone());
49        }
50
51        if !config.headers.is_empty() {
52            client = client.default_headers(config.headers.clone());
53        }
54
55        if let Some(timeout) = config.timeout {
56            client = client.timeout(timeout);
57        }
58
59        if let Some(connect_timeout) = config.connect_timeout {
60            client = client.connect_timeout(connect_timeout);
61        }
62
63        client = client.connection_verbose(config.connection_verbose);
64
65        let url = config.url.expect("missing url");
66        let path = config.path.unwrap_or(String::new());
67        let client = Arc::new(Mutex::new(client.build().expect("failed to build async client")));
68
69        AsyncClient { client, url, path }
70    }
71
72}