xitca_service/middleware/
map.rs1use crate::{
2 pipeline::{PipelineT, marker},
3 service::Service,
4};
5
6pub struct Map<F>(pub F);
7
8impl<F> Clone for Map<F>
9where
10 F: Clone,
11{
12 fn clone(&self) -> Self {
13 Self(self.0.clone())
14 }
15}
16
17impl<S, E, F> Service<Result<S, E>> for Map<F>
18where
19 F: Clone,
20{
21 type Response = PipelineT<S, F, marker::Map>;
22 type Error = E;
23
24 async fn call(&self, arg: Result<S, E>) -> Result<Self::Response, Self::Error> {
25 arg.map(|service| PipelineT::new(service, self.0.clone()))
26 }
27}
28
29impl<S, Req, F, Res> Service<Req> for PipelineT<S, F, marker::Map>
30where
31 S: Service<Req>,
32 F: Fn(S::Response) -> Res,
33{
34 type Response = Res;
35 type Error = S::Error;
36
37 #[inline]
38 async fn call(&self, req: Req) -> Result<Self::Response, Self::Error> {
39 self.first.call(req).await.map(&self.second)
40 }
41}
42
43#[derive(Clone)]
44pub struct MapErr<F>(pub F);
45
46impl<S, E, F> Service<Result<S, E>> for MapErr<F>
47where
48 F: Clone,
49{
50 type Response = PipelineT<S, F, marker::MapErr>;
51 type Error = E;
52
53 async fn call(&self, arg: Result<S, E>) -> Result<Self::Response, Self::Error> {
54 arg.map(|service| PipelineT::new(service, self.0.clone()))
55 }
56}
57
58impl<S, Req, F, Err> Service<Req> for PipelineT<S, F, marker::MapErr>
59where
60 S: Service<Req>,
61 F: Fn(S::Error) -> Err,
62{
63 type Response = S::Response;
64 type Error = Err;
65
66 #[inline]
67 async fn call(&self, req: Req) -> Result<Self::Response, Self::Error> {
68 self.first.call(req).await.map_err(&self.second)
69 }
70}