use std::future::Future;
use zon_core::{HttpMiddleware, HttpService};
#[derive(Clone, Copy, Debug)]
pub struct MapResponse<F> {
map_fn: F,
}
impl<F> MapResponse<F> {
pub fn new(map_fn: F) -> Self {
Self { map_fn }
}
}
impl<S, F> HttpMiddleware<S> for MapResponse<F> {
type Service = MapResponseService<S, F>;
fn apply(self, inner: S) -> Self::Service {
MapResponseService::new(inner, self.map_fn)
}
}
pub struct MapResponseService<S, F> {
inner: S,
map_fn: F,
}
impl<S, F> MapResponseService<S, F> {
pub fn new(inner: S, map_fn: F) -> Self {
Self { inner, map_fn }
}
}
impl<S, F, Fut, B, ResB> HttpService<B> for MapResponseService<S, F>
where
S: HttpService<B>,
F: Fn(http::Response<S::ResponseBody>) -> Fut + Sync,
Fut: Future<Output = http::Response<ResB>> + Send,
B: Send,
{
type ResponseBody = ResB;
async fn call(&self, request: http::Request<B>) -> http::Response<Self::ResponseBody> {
let response = self.inner.call(request).await;
(self.map_fn)(response).await
}
}