Skip to main content

apply

Function apply 

Source
pub fn apply<Sf, St, Req, M>(
    mw: M,
    factory: impl IntoServiceFactory<Sf, St, Req>,
) -> ServiceChainFactory<ApplyMiddleware<M, Sf>, St, Req>
where Sf: ServiceFactory<St, Req>, M: Middleware<Sf::Service, St>,
Expand description

Applies middleware to every service produced by a factory.

Returns a ServiceChainFactory containing an ApplyMiddleware. Creation first awaits the inner factory, then calls Middleware::create synchronously with the new service and the same state reference. If the factory fails, its initialization error is returned without invoking the middleware.

To use the result as a ServiceFactory, the middleware’s service must accept the same state and request types as the inner service. Response and service-error types may change. The wrapper is responsible for forwarding calls, binding, readiness, and shutdown as appropriate.

Cloning the resulting factory shares the middleware and inner factory through Rc; neither needs to implement Clone.

§Example

use ntex_service::{Identity, apply, fn_factory, fn_service};

let factory = apply(
    Identity,
    fn_factory(async |offset: &u32| {
        let offset = *offset;
        Ok::<_, ()>(fn_service(async move |req: u32| Ok::<_, ()>(req + offset)))
    }),
);

let pipeline = factory.pipeline(10).await?;
assert_eq!(pipeline.call(2).await?, 12);