use crate::{Request, Response};
use rama_core::{Layer, Service, bytes::Bytes, error::BoxError};
use rama_http_types::StreamingBody;
use rama_utils::macros::define_inner_service_accessors;
use std::fmt;
#[derive(Clone)]
pub struct MapRequestBodyLayer<F> {
f: F,
}
impl<F> MapRequestBodyLayer<F> {
pub const fn new(f: F) -> Self {
Self { f }
}
}
impl<Body> MapRequestBodyLayer<fn(Body) -> crate::Body>
where
Body: StreamingBody<Data = Bytes, Error: Into<BoxError>> + Send + Sync + 'static,
{
pub const fn new_boxed_streaming_body() -> Self {
Self::new(crate::Body::new)
}
}
impl<Body> MapRequestBodyLayer<fn(Body) -> crate::Body>
where
crate::Body: From<Body>,
{
pub const fn into_boxed_streaming_body() -> Self {
Self::new(crate::Body::from)
}
}
impl<S, F> Layer<S> for MapRequestBodyLayer<F>
where
F: Clone,
{
type Service = MapRequestBody<S, F>;
fn layer(&self, inner: S) -> Self::Service {
MapRequestBody::new(inner, self.f.clone())
}
fn into_layer(self, inner: S) -> Self::Service {
MapRequestBody::new(inner, self.f)
}
}
impl<F> fmt::Debug for MapRequestBodyLayer<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapRequestBodyLayer")
.field("f", &std::any::type_name::<F>())
.finish()
}
}
#[derive(Clone)]
pub struct MapRequestBody<S, F> {
inner: S,
f: F,
}
impl<S, F> MapRequestBody<S, F> {
pub const fn new(service: S, f: F) -> Self {
Self { inner: service, f }
}
define_inner_service_accessors!();
}
impl<S, Body> MapRequestBody<S, fn(Body) -> crate::Body>
where
Body: StreamingBody<Data = Bytes, Error: Into<BoxError>> + Send + Sync + 'static,
{
pub const fn new_boxed_streaming_body(inner: S) -> Self {
Self::new(inner, crate::Body::new)
}
}
impl<S, Body> MapRequestBody<S, fn(Body) -> crate::Body>
where
crate::Body: From<Body>,
{
pub const fn into_boxed_streaming_body(inner: S) -> Self {
Self::new(inner, crate::Body::from)
}
}
impl<F, S, ReqBody, ResBody, NewReqBody> Service<Request<ReqBody>> for MapRequestBody<S, F>
where
S: Service<Request<NewReqBody>, Output = Response<ResBody>>,
ReqBody: Send + 'static,
NewReqBody: Send + 'static,
ResBody: Send + Sync + 'static,
F: Fn(ReqBody) -> NewReqBody + Send + Sync + 'static,
{
type Output = S::Output;
type Error = S::Error;
async fn serve(&self, req: Request<ReqBody>) -> Result<Self::Output, Self::Error> {
let req = req.map(&self.f);
self.inner.serve(req).await
}
}
impl<S, F> fmt::Debug for MapRequestBody<S, F>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapRequestBody")
.field("inner", &self.inner)
.field("f", &std::any::type_name::<F>())
.finish()
}
}