Skip to main content

openapi_contract/
client.rs

1use std::future::Future;
2
3use crate::error::ApiError;
4use crate::sse::SseStream;
5
6/// HTTP method for API requests.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum Method {
9    GET,
10    POST,
11    PUT,
12    DELETE,
13    PATCH,
14    HEAD,
15    OPTIONS,
16}
17
18impl Method {
19    pub fn as_reqwest(&self) -> reqwest::Method {
20        match self {
21            Self::GET => reqwest::Method::GET,
22            Self::POST => reqwest::Method::POST,
23            Self::PUT => reqwest::Method::PUT,
24            Self::DELETE => reqwest::Method::DELETE,
25            Self::PATCH => reqwest::Method::PATCH,
26            Self::HEAD => reqwest::Method::HEAD,
27            Self::OPTIONS => reqwest::Method::OPTIONS,
28        }
29    }
30}
31
32/// Trait for making async API requests.
33///
34/// Implement this for your HTTP client (e.g. a wrapper around `reqwest::Client`).
35pub trait ApiClient: Send + Sync {
36    fn request(
37        &self,
38        method: Method,
39        path: &str,
40        query: Option<&str>,
41        body: Option<String>,
42    ) -> impl Future<Output = Result<reqwest::Response, ApiError>> + Send;
43
44    fn request_stream(
45        &self,
46        method: Method,
47        path: &str,
48        query: Option<&str>,
49    ) -> impl Future<Output = Result<SseStream, ApiError>> + Send;
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn method_conversions_and_traits() {
58        // as_reqwest covers all variants
59        assert_eq!(Method::GET.as_reqwest(), reqwest::Method::GET);
60        assert_eq!(Method::POST.as_reqwest(), reqwest::Method::POST);
61        assert_eq!(Method::PUT.as_reqwest(), reqwest::Method::PUT);
62        assert_eq!(Method::DELETE.as_reqwest(), reqwest::Method::DELETE);
63        assert_eq!(Method::PATCH.as_reqwest(), reqwest::Method::PATCH);
64        assert_eq!(Method::HEAD.as_reqwest(), reqwest::Method::HEAD);
65        assert_eq!(Method::OPTIONS.as_reqwest(), reqwest::Method::OPTIONS);
66
67        // Debug, Eq, Copy
68        assert_eq!(format!("{:?}", Method::GET), "GET");
69        assert_eq!(Method::GET, Method::GET);
70        assert_ne!(Method::GET, Method::POST);
71        let m = Method::PUT;
72        let m2 = m;
73        assert_eq!(m, m2);
74    }
75}