Skip to main content

serenade_http_client/
compile_pass.rs

1//! DI tag and compile pass for the default outbound HTTP client.
2
3use std::sync::Arc;
4
5#[cfg(feature = "reqwest")]
6use serenade_di::ServiceDefinition;
7use serenade_di::{CompilePass, ContainerBuilder, DiError};
8
9use crate::DynHttpClient;
10
11/// Service tag applied to outbound HTTP client definitions.
12pub const HTTP_CLIENT_TAG: &str = "http.client";
13
14/// Container id of the default outbound client when registered by the pass.
15pub const DEFAULT_HTTP_CLIENT_SERVICE: &str = "http_client";
16
17/// Newtype so client trait objects can be stored in the container.
18#[derive(Clone)]
19pub struct HttpClientService(pub Arc<dyn DynHttpClient>);
20
21impl HttpClientService {
22    /// Sends through the wrapped client.
23    ///
24    /// # Errors
25    ///
26    /// Propagates [`crate::HttpClientError`] from the client.
27    pub fn send(
28        &self,
29        request: crate::ClientRequest,
30    ) -> impl std::future::Future<Output = Result<crate::ClientResponse, crate::HttpClientError>>
31    + Send
32    + '_ {
33        self.0.send_boxed(request)
34    }
35
36    /// Convenience GET.
37    ///
38    /// # Errors
39    ///
40    /// Propagates [`Self::send`].
41    pub fn get(
42        &self,
43        url: impl Into<String> + Send,
44    ) -> impl std::future::Future<Output = Result<crate::ClientResponse, crate::HttpClientError>>
45    + Send
46    + '_ {
47        self.send(crate::ClientRequest::get(url))
48    }
49
50    /// Convenience POST with body bytes.
51    ///
52    /// # Errors
53    ///
54    /// Propagates [`Self::send`].
55    pub fn post(
56        &self,
57        url: impl Into<String> + Send,
58        body: impl Into<Vec<u8>> + Send,
59    ) -> impl std::future::Future<Output = Result<crate::ClientResponse, crate::HttpClientError>>
60    + Send
61    + '_ {
62        self.send(crate::ClientRequest::post(url).body(body))
63    }
64}
65
66/// Seeds [`DEFAULT_HTTP_CLIENT_SERVICE`] with a [`crate::ReqwestHttpClient`] when missing.
67///
68/// Requires Cargo feature `reqwest` (on by default). Without that feature the pass is a no-op.
69#[derive(Debug, Default)]
70pub struct RegisterDefaultHttpClientPass;
71
72impl CompilePass for RegisterDefaultHttpClientPass {
73    fn name(&self) -> &'static str {
74        "register_default_http_client"
75    }
76
77    fn process(&self, builder: &mut ContainerBuilder) -> Result<(), DiError> {
78        let has_default = builder
79            .definitions()
80            .iter()
81            .any(|definition| definition.id() == DEFAULT_HTTP_CLIENT_SERVICE);
82        if has_default {
83            return Ok(());
84        }
85
86        #[cfg(feature = "reqwest")]
87        // `expect`: default id cannot collide after the has_default guard above.
88        builder
89            .register(
90                ServiceDefinition::new(DEFAULT_HTTP_CLIENT_SERVICE).with_tag(HTTP_CLIENT_TAG),
91                |_container| {
92                    Ok(Box::new(HttpClientService(
93                        Arc::new(crate::ReqwestHttpClient::new()) as Arc<dyn DynHttpClient>,
94                    )))
95                },
96            )
97            .expect("default http_client id is unique");
98
99        Ok(())
100    }
101}