use crate::{Request, Response};
use rama_core::{Context, Layer, Service};
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<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<F, S, State, ReqBody, ResBody, NewResBody> Service<State, Request<ReqBody>>
for MapResponseBody<S, F>
where
S: Service<State, Request<ReqBody>, Response = Response<ResBody>>,
State: Clone + Send + Sync + 'static,
ReqBody: Send + 'static,
ResBody: Send + Sync + 'static,
NewResBody: Send + Sync + 'static,
F: Fn(ResBody) -> NewResBody + Clone + Send + Sync + 'static,
{
type Response = Response<NewResBody>;
type Error = S::Error;
async fn serve(
&self,
ctx: Context<State>,
req: Request<ReqBody>,
) -> Result<Self::Response, Self::Error> {
let res = self.inner.serve(ctx, 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()
}
}