clientix_core/client/blocking/
request.rs1use http::Method;
2use crate::client::blocking::client::BlockingClient;
3use crate::client::blocking::response::BlockingResponseHandler;
4use crate::client::request::{ClientixRequestBuilder, RequestConfig};
5use crate::client::response::{ClientixError, ClientixErrorData, ClientixResult};
6
7pub struct BlockingRequest {
8 client: BlockingClient,
9 method: Method,
10 config: RequestConfig,
11 result: ClientixResult<()>,
12}
13
14impl ClientixRequestBuilder for BlockingRequest {
15
16 fn config(&mut self) -> &mut RequestConfig {
17 &mut self.config
18 }
19
20 fn result(&mut self) -> &mut ClientixResult<()> {
21 &mut self.result
22 }
23
24}
25
26impl BlockingRequest {
27
28 pub fn new(client: BlockingClient, method: Method) -> Self {
29 BlockingRequest {
30 client,
31 method,
32 config: Default::default(),
33 result: Ok(())
34 }
35 }
36
37 pub fn builder(client: BlockingClient, method: Method) -> Self {
38 BlockingRequest::new(client, method)
39 }
40
41 pub fn send(self) -> BlockingResponseHandler {
42 if let Err(error) = self.result {
43 return BlockingResponseHandler::new(Err(error));
44 }
45
46 let full_path = format!("{}{}", self.client.path, self.config.get_path());
47 let url = format!("{}{}", self.client.url, full_path);
48
49 match self.client.client.lock() {
50 Ok(client) => {
51 let mut request_builder = match self.method {
52 Method::GET => client.get(url.clone()),
53 Method::POST => client.post(url.clone()),
54 Method::PUT => client.put(url.clone()),
55 Method::DELETE => client.delete(url.clone()),
56 Method::HEAD => client.head(url.clone()),
57 Method::PATCH => client.patch(url.clone()),
58 _ => {
59 let error_data = ClientixErrorData::builder().message(format!("invalid method: {:?}", self.method).as_str()).build();
60 return BlockingResponseHandler::new(Err(ClientixError::InvalidRequest(error_data, None)));
61 },
62 };
63
64 request_builder = request_builder
65 .headers(self.config.get_headers().clone())
66 .query(self.config.get_queries());
67
68 request_builder = match self.config.get_body() {
69 Some(body) => request_builder.body::<String>(body.into()),
70 None => request_builder,
71 };
72
73 request_builder = match self.config.get_timeout() {
74 Some(timeout) => request_builder.timeout(timeout),
75 None => request_builder,
76 };
77
78 match request_builder.send() {
79 Ok(response) => BlockingResponseHandler::new(Ok(response)),
80 Err(error) => BlockingResponseHandler::new(Err(ClientixError::Http(ClientixErrorData::new(), Some(error.into()))))
81 }
82 },
83 Err(error) => {
84 let error_data = ClientixErrorData::builder().message(format!("client locked: {:?}", error).as_str()).build();
85 BlockingResponseHandler::new(Err(ClientixError::Other(error_data, None)))
86 }
87 }
88 }
89
90}