use std::future::Future;
use http::{Method, Uri};
use tower_service::Service;
use super::{ClientRequest, IntoUri, client_request::ClientRequestBuilder};
#[doc = include_utils::include_md!("README.md:example")]
pub trait ServiceExt<ReqBody, RespBody, Err>: Sized {
fn execute<R>(
&mut self,
request: http::Request<R>,
) -> impl Future<Output = Result<http::Response<RespBody>, Err>>
where
ReqBody: From<R>;
fn request<U>(
&mut self,
method: Method,
uri: U,
) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
ClientRequest::builder(self).method(method).uri(uri)
}
fn get<U>(&mut self, uri: U) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
self.request(Method::GET, uri)
}
fn put<U>(&mut self, uri: U) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
self.request(Method::PUT, uri)
}
fn post<U>(&mut self, uri: U) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
self.request(Method::POST, uri)
}
fn patch<U>(&mut self, uri: U) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
self.request(Method::PATCH, uri)
}
fn delete<U>(&mut self, uri: U) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
self.request(Method::DELETE, uri)
}
fn head<U>(&mut self, uri: U) -> ClientRequestBuilder<'_, Self, Err, RespBody>
where
U: IntoUri,
Uri: TryFrom<U::TryInto>,
<Uri as TryFrom<U::TryInto>>::Error: Into<http::Error>,
{
self.request(Method::HEAD, uri)
}
}
impl<S, ReqBody, RespBody, Err> ServiceExt<ReqBody, RespBody, Err> for S
where
S: Service<http::Request<ReqBody>, Response = http::Response<RespBody>, Error = Err>,
S::Future: Send + 'static,
S::Error: 'static,
{
async fn execute<R>(
&mut self,
request: http::Request<R>,
) -> Result<http::Response<RespBody>, Err>
where
ReqBody: From<R>,
{
futures_util::future::poll_fn(|ctx| self.poll_ready(ctx)).await?;
self.call(request.map(ReqBody::from)).await
}
}