simbld_http/responses/
wrapper.rs

1/// This module provides functions to generate HTTP response functions based on enum variants.
2///
3/// # Functions
4///
5/// - `generate_responses`: Generates functions that return a tuple containing the HTTP status code and a static string representation of the variant.
6/// - `generate_responses_with_metadata`: Generates functions that return a string response enriched with metadata.
7///
8/// # Example
9///
10/// ```rust
11///
12/// let responses = generate_responses();
13/// println!("{}", responses);
14///
15/// let responses_with_metadata = generate_responses_with_metadata();
16/// println!("{}", responses_with_metadata);
17/// ```
18///
19/// # Details
20///
21/// Both functions iterate over all variants of an enum `T` and generate two functions for each variant:
22/// one with a snake_case name and one with a CamelCase name. The `generate_responses` function creates
23/// functions that return a tuple `(u16, &'static str)`, while the `generate_responses_with_metadata` function
24/// creates functions that return a string enriched with metadata.
25use inflector::Inflector;
26use strum::IntoEnumIterator;
27
28pub struct ResponseWrapper<T>(pub T);
29
30impl<T> ResponseWrapper<T>
31where
32  T: IntoEnumIterator + std::fmt::Debug + Copy + ToString + Into<u16>,
33{
34  pub fn generate_responses() -> String {
35    let mut output = String::new();
36    let variants = T::iter().collect::<Vec<_>>(); // Collect all variations
37    for variant in variants {
38      let function_name_snake = variant.to_string().to_snake_case();
39      let function_name_camel = variant.to_string().to_camel_case();
40      let code: u16 = variant.into();
41
42      output.push_str(&format!(
43        "fn {}() -> (u16, &'static str) {{ ({}, {:?}) }}\n",
44        function_name_snake, code, variant
45      ));
46      output.push_str(&format!(
47        "fn {}() -> (u16, &'static str) {{ ({}, {:?}) }}\n",
48        function_name_camel, code, variant
49      ));
50    }
51    output
52  }
53
54  pub fn generate_responses_with_metadata() -> String {
55    let mut output = String::new();
56    let variants = T::iter().collect::<Vec<_>>(); // Collect all variations
57    for variant in variants {
58      let function_name_snake = variant.to_string().to_snake_case();
59      let function_name_camel = variant.to_string().to_camel_case();
60      let code: u16 = variant.into();
61
62      output.push_str(&format!(
63                "fn {}() -> String {{ response_helpers::get_enriched_response_with_metadata({}, None, std::time::Duration::from_millis(100)) }}\n",
64                function_name_snake, code
65            ));
66      output.push_str(&format!(
67                "fn {}() -> String {{ response_helpers::get_enriched_response_with_metadata({}, None, std::time::Duration::from_millis(100)) }}\n",
68                function_name_camel, code
69            ));
70    }
71    output
72  }
73}
74
75#[cfg(test)]
76mod tests {
77  use crate::mocks::mock_responses::MockResponses;
78  use crate::responses::wrapper::ResponseWrapper;
79
80  #[test]
81  fn test_generate_responses() {
82    let output = ResponseWrapper::<MockResponses>::generate_responses();
83
84    assert!(output.contains("fn ok() -> (u16, &'static str) { (200, Ok) }"));
85    assert!(output.contains("fn bad_request() -> (u16, &'static str) { (400, BadRequest) }"));
86    assert!(output.contains("fn unauthorized() -> (u16, &'static str) { (401, Unauthorized) }"));
87    assert!(output.contains("fn not_found() -> (u16, &'static str) { (404, NotFound) }"));
88    assert!(output.contains(
89      "fn internal_server_error() -> (u16, &'static str) { (500, InternalServerError) }"
90    ));
91  }
92
93  #[test]
94  fn test_generate_responses_with_metadata() {
95    let output = ResponseWrapper::<MockResponses>::generate_responses_with_metadata();
96
97    assert!(output.contains("fn ok() -> String { response_helpers::get_enriched_response_with_metadata(200, None, std::time::Duration::from_millis(100)) }"));
98    assert!(output.contains("fn bad_request() -> String { response_helpers::get_enriched_response_with_metadata(400, None, std::time::Duration::from_millis(100)) }"));
99    assert!(output.contains("fn unauthorized() -> String { response_helpers::get_enriched_response_with_metadata(401, None, std::time::Duration::from_millis(100)) }"));
100    assert!(output.contains("fn not_found() -> String { response_helpers::get_enriched_response_with_metadata(404, None, std::time::Duration::from_millis(100)) }"));
101    assert!(output.contains("fn internal_server_error() -> String { response_helpers::get_enriched_response_with_metadata(500, None, std::time::Duration::from_millis(100)) }"));
102  }
103}