request_builder_ext.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //! HTTP RequestBuilder extension trait
  2. use serde::de::DeserializeOwned;
  3. use serde::Serialize;
  4. use crate::response::{RawResponse, Response};
  5. /// Trait for building and sending HTTP requests
  6. ///
  7. /// This trait abstracts over different HTTP client backends (bitreq, reqwest)
  8. /// and provides a unified interface for building and sending HTTP requests.
  9. pub trait RequestBuilderExt: Sized + Send {
  10. /// Add a header to the request
  11. fn header(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self;
  12. /// Set the request body as JSON
  13. fn json<T: Serialize>(self, body: &T) -> Self;
  14. /// Set the request body as form data
  15. fn form<T: Serialize>(self, body: &T) -> Self;
  16. /// Send the request and return a raw response
  17. fn send(self) -> impl std::future::Future<Output = Response<RawResponse>> + Send;
  18. /// Send the request and deserialize the response as JSON
  19. fn send_json<R: DeserializeOwned>(
  20. self,
  21. ) -> impl std::future::Future<Output = Response<R>> + Send;
  22. }
  23. #[allow(clippy::manual_async_fn)]
  24. impl<T: RequestBuilderExt> RequestBuilderExt for Box<T> {
  25. fn header(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
  26. Box::new((*self).header(key, value))
  27. }
  28. fn json<B: Serialize>(self, body: &B) -> Self {
  29. Box::new((*self).json(body))
  30. }
  31. fn form<F: Serialize>(self, body: &F) -> Self {
  32. Box::new((*self).form(body))
  33. }
  34. fn send(self) -> impl std::future::Future<Output = Response<RawResponse>> + Send {
  35. async move { (*self).send().await }
  36. }
  37. fn send_json<R: DeserializeOwned>(
  38. self,
  39. ) -> impl std::future::Future<Output = Response<R>> + Send {
  40. async move { (*self).send_json().await }
  41. }
  42. }