reqwest_enum/
http.rs

1use reqwest::Method;
2use crate::provider::ProviderRequestBuilder;
3
4#[derive(Debug, Default)]
5pub struct HTTPBody {
6    pub inner: reqwest::Body,
7}
8
9impl HTTPBody {
10    pub fn to_bytes(&self) -> Vec<u8> {
11        self.inner.as_bytes().unwrap_or_default().to_vec()
12    }
13}
14
15pub type HTTPResponse = reqwest::Response;
16
17pub enum HTTPMethod {
18    GET,
19    POST,
20    PUT,
21    DELETE,
22    PATCH,
23    OPTIONS,
24    HEAD,
25    CONNECT,
26}
27
28impl std::fmt::Display for HTTPMethod {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        let s = match self {
31            HTTPMethod::GET => "GET",
32            HTTPMethod::POST => "POST",
33            HTTPMethod::PUT => "PUT",
34            HTTPMethod::DELETE => "DELETE",
35            HTTPMethod::PATCH => "PATCH",
36            HTTPMethod::OPTIONS => "OPTIONS",
37            HTTPMethod::HEAD => "HEAD",
38            HTTPMethod::CONNECT => "CONNECT",
39        };
40        write!(f, "{}", s)
41    }
42}
43
44impl From<HTTPMethod> for Method {
45    fn from(val: HTTPMethod) -> Self {
46        match val {
47            HTTPMethod::GET => Method::GET,
48            HTTPMethod::POST => Method::POST,
49            HTTPMethod::PUT => Method::PUT,
50            HTTPMethod::DELETE => Method::DELETE,
51            HTTPMethod::PATCH => Method::PATCH,
52            HTTPMethod::OPTIONS => Method::OPTIONS,
53            HTTPMethod::HEAD => Method::HEAD,
54            HTTPMethod::CONNECT => Method::CONNECT,
55        }
56    }
57}
58
59impl HTTPBody {
60    pub fn from<S: serde::Serialize>(value: &S) -> Result<Self, serde_json::Error> {
61        let mut writer = Vec::new();
62        serde_json::to_writer(&mut writer, value)?;
63        Ok(Self { inner: writer.into() })
64    }
65
66    pub fn from_array<S: serde::Serialize>(array: &[S]) -> Result<Self, serde_json::Error> {
67        let mut writer = Vec::new();
68        serde_json::to_writer(&mut writer, array)?;
69        Ok(Self { inner: writer.into() })
70    }
71}
72
73/// Authentication method for a request (Basic, Bearer, or Custom closure).
74pub enum AuthMethod {
75    /// HTTP Basic authentication.
76    /// Takes a username (`String`) and an optional password (`Option<String>`).
77    Basic(String, Option<String>),
78    /// HTTP Bearer authentication.
79    /// Takes a token (`String`).
80    Bearer(String),
81    /// Custom authentication logic provided as a closure.
82    /// The closure takes a `reqwest::RequestBuilder` and returns a modified `reqwest::RequestBuilder`.
83    /// This allows for flexible and complex authentication mechanisms.
84    /// 
85    /// # Example
86    ///
87    /// ```rust,ignore
88    /// AuthMethod::Custom(Box::new(|rb| rb.header("X-Custom-Auth", "some_value")))
89    /// ```
90    Custom(Box<dyn Fn(ProviderRequestBuilder) -> ProviderRequestBuilder + Send + Sync + 'static>),
91}
92
93impl AuthMethod {
94    /// Helper for `AuthMethod::Custom`: API key authentication via a request header.
95    ///
96    /// # Example
97    ///
98    /// ```rust,ignore
99    /// use reqwest_enum::http::AuthMethod;
100    ///
101    /// let auth = AuthMethod::header_api_key("Authorization".to_string(), "mysecretapikey".to_string());
102    /// // This can then be returned by a Target's `authentication()` method.
103    /// ```
104    pub fn header_api_key(header_name: String, api_key: String) -> Self {
105        AuthMethod::Custom(Box::new(
106            move |rb: ProviderRequestBuilder| {
107                rb.header(header_name.clone(), api_key.clone())
108            },
109        ))
110    }
111}
112
113impl std::fmt::Debug for AuthMethod {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        match self {
116            AuthMethod::Basic(username, password) => f
117                .debug_tuple("Basic")
118                .field(username)
119                .field(password)
120                .finish(),
121            AuthMethod::Bearer(token) => f.debug_tuple("Bearer").field(token).finish(),
122            AuthMethod::Custom(_) => f.debug_tuple("Custom").field(&"<function>").finish(),
123        }
124    }
125}