termii_rust/
macros.rs

1// A macro to try to parse a response from the API.
2// we pass the response and the expected type of the response
3// if parsing fails, we return the string response wrapped in HttpError
4
5#[allow(unused_macros)]
6macro_rules! response_or_error_text_blocking {
7    ($response:expr, $expected_type:ty) => {
8        // first we store the response in a variable as a string
9        {
10            let status_code = $response.status();
11            let response_text = $response.text().unwrap();
12            let response_data = serde_json::from_str::<$expected_type>(&response_text);
13
14            match response_data {
15                Ok(response_data) => response_data,
16                Err(e) => {
17                    println!("{}", e);
18                    return Err(errors::HttpError::JsonError {
19                        status: status_code.as_u16() as usize,
20                        message: response_text.to_string(),
21                    });
22                }
23            }
24        }
25    };
26}
27
28macro_rules! response_or_error_text_async {
29    ($response:expr, $expected_type:ty) => {{
30        let status_code = $response.status();
31        let response_text = $response.text().await.unwrap();
32        let response_data = serde_json::from_str::<$expected_type>(&response_text);
33
34        match response_data {
35            Ok(response_data) => response_data,
36            Err(e) => {
37                println!("{}", e);
38                return Err(errors::HttpError::JsonError {
39                    status: status_code.as_u16() as usize,
40                    message: response_text.to_string(),
41                });
42            }
43        }
44    }};
45}