Skip to main content

forward

Macro forward 

Source
macro_rules! forward {
    (@go $st:ty; [$field:tt]; map_err = $err:expr $(,)?) => { ... };
    (@go $st:ty; [$($field:tt)+]; map_err = $err:expr $(,)?) => { ... };
    (@go $st:ty; []; map_err $($rest:tt)*) => { ... };
    (@go $st:ty; [$($field:tt)*]; self . $($rest:tt)*) => { ... };
    (@go $st:ty; [$($field:tt)*]; $next:tt . $($rest:tt)*) => { ... };
    (@go $st:ty; [$($field:tt)+]; ) => { ... };
    (@go $st:ty; [$($field:tt)*]; $next:tt $(, $($rest:tt)*)?) => { ... };
    (@ready $ctx:ident, $this:tt, $err:expr; $field:tt) => { ... };
    (@ready $ctx:ident, $this:tt, $err:expr; $field:tt $($rest:tt)+) => { ... };
    (@shutdown $ctx:ident, $this:tt; $field:tt) => { ... };
    (@shutdown $ctx:ident, $this:tt; $field:tt $($rest:tt)+) => { ... };
    ($one:tt $(,)?) => { ... };
    ($st:ty, $($rest:tt)+) => { ... };
}
Expand description

Forwards crate::Service::bind, crate::Service::ready, and crate::Service::shutdown to inner service fields.

This is the recommended way to write a wrapper service. For a crate::Pipeline field implement bind with crate::Pipeline::bind_to.

  • forward!(St, field): forwards to a service field, readiness errors are converted with Into.
  • forward!(St, a, b, ...): forwards to several service fields. Readiness completes once all fields are ready, and shutdown waits for all of them.
  • forward!(St, field, ..., map_err = f): converts readiness errors with f.

St is the state type of the Service<St, Req> impl, and each field is a named or tuple field such as inner or 0. Call the inner services with crate::Ctx::call.

use ntex_service::{Ctx, Service, forward};

struct Log<S>(S);

impl<S, St, Req> Service<St, Req> for Log<S>
where
    S: Service<St, Req>,
{
    type Res = S::Res;
    type Error = S::Error;

    forward!(St, 0);

    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, S::Error> {
        println!("call");
        ctx.call(&self.0, req).await
    }
}

struct Both<A, B> {
    first: A,
    second: B,
}

impl<A, B, St, Req> Service<St, Req> for Both<A, B>
where
    A: Service<St, Req, Res = Req>,
    B: Service<St, Req, Error = A::Error>,
{
    type Res = B::Res;
    type Error = String;

    forward!(St, first, second, map_err = |_| "not ready".to_string());

    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<B::Res, String> {
        let req = ctx.call(&self.first, req).await.map_err(|_| "first".to_string())?;
        ctx.call(&self.second, req).await.map_err(|_| "second".to_string())
    }
}