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 MapResponseBodyLayer<F> {
f: F,
}
impl<F> MapResponseBodyLayer<F> {
pub const fn new(f: F) -> Self {
Self { f }
}
}
impl<Body> MapResponseBodyLayer<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> MapResponseBodyLayer<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 MapResponseBodyLayer<F>
where
F: Clone,
{
type Service = MapResponseBody<S, F>;
fn layer(&self, inner: S) -> Self::Service {
MapResponseBody::new(inner, self.f.clone())
}
fn into_layer(self, inner: S) -> Self::Service {
MapResponseBody::new(inner, self.f)
}
}
impl<F> fmt::Debug for MapResponseBodyLayer<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapResponseBodyLayer")
.field("f", &std::any::type_name::<F>())
.finish()
}
}
#[derive(Clone)]
pub struct MapResponseBody<S, F> {
inner: S,
f: F,
}
impl<S, F> MapResponseBody<S, F> {
pub const fn new(service: S, f: F) -> Self {
Self { inner: service, f }
}
define_inner_service_accessors!();
}
impl<S, Body> MapResponseBody<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> MapResponseBody<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, NewResBody> Service<Request<ReqBody>> for MapResponseBody<S, F>
where
S: Service<Request<ReqBody>, Output = Response<ResBody>>,
ReqBody: Send + 'static,
ResBody: Send + Sync + 'static,
NewResBody: Send + Sync + 'static,
F: Fn(ResBody) -> NewResBody + Clone + Send + Sync + 'static,
{
type Output = Response<NewResBody>;
type Error = S::Error;
async fn serve(&self, req: Request<ReqBody>) -> Result<Self::Output, Self::Error> {
let res = self.inner.serve(req).await?;
Ok(res.map(self.f.clone()))
}
}
impl<S, F> fmt::Debug for MapResponseBody<S, F>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapResponseBody")
.field("inner", &self.inner)
.field("f", &std::any::type_name::<F>())
.finish()
}
}