use crate::{Layer, Service};
use core::fmt;
use rama_utils::macros::define_inner_service_accessors;
#[derive(Clone)]
pub struct MapResult<S, F> {
inner: S,
f: F,
}
impl<S, F> fmt::Debug for MapResult<S, F>
where
S: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapResult")
.field("inner", &self.inner)
.field("f", &format_args!("{}", core::any::type_name::<F>()))
.finish()
}
}
#[derive(Clone)]
pub struct MapResultLayer<F> {
f: F,
}
impl<F> fmt::Debug for MapResultLayer<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapResultLayer")
.field("f", &format_args!("{}", core::any::type_name::<F>()))
.finish()
}
}
impl<S, F> MapResult<S, F> {
pub const fn new(inner: S, f: F) -> Self {
Self { f, inner }
}
define_inner_service_accessors!();
}
impl<S, F, Input, Output, Error> Service<Input> for MapResult<S, F>
where
S: Service<Input>,
F: Fn(Result<S::Output, S::Error>) -> Result<Output, Error> + Send + Sync + 'static,
Input: Send + 'static,
Output: Send + 'static,
Error: Send + 'static,
{
type Output = Output;
type Error = Error;
async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
let result = self.inner.serve(input).await;
(self.f)(result)
}
}
impl<F> MapResultLayer<F> {
pub const fn new(f: F) -> Self {
Self { f }
}
}
impl<S, F> Layer<S> for MapResultLayer<F>
where
F: Clone,
{
type Service = MapResult<S, F>;
fn layer(&self, inner: S) -> Self::Service {
MapResult {
f: self.f.clone(),
inner,
}
}
fn into_layer(self, inner: S) -> Self::Service {
MapResult { f: self.f, inner }
}
}