pub fn apply_fn<S, St, Req, F, In, Out, Err>(
service: impl IntoService<S, St, Req>,
f: F,
) -> ServiceChain<Apply<S, St, Req, F, In, Out, Err>, St, In>Expand description
Applies an asynchronous middleware function to a service.
The function receives an input request and an ApplyCtx with access to
the pipeline state and inner service. It can adapt the request, transform
the response or error, and decide whether and how often to call the inner
service. The state type stays the same; the request, response, and error
types can differ from those of the inner service.
Returns a ServiceChain containing an Apply service. Binding and
shutdown are forwarded to the inner service. Readiness is also forwarded,
with inner readiness errors converted into the middleware’s error type
through From. Errors from ApplyCtx::call retain the inner error
type, so the middleware can handle or convert them.
§Readiness
The enclosing pipeline checks readiness before invoking the middleware.
ApplyCtx::call forwards directly to the inner service; it does not add
another readiness check for a raw service. Wrap the inner service with
crate::ready() when calls need their own readiness check, including
after the middleware awaits other work or makes an earlier call.
§Example
use ntex_service::{Service, apply_fn, fn_service};
let service = apply_fn(
fn_service(async |req: u32| Ok::<_, ()>(req + 1)),
async |req: &str, ctx| {
let value = req.parse::<u32>().map_err(|_| ())?;
let response = ctx.call(value).await?;
Ok::<_, ()>(response.to_string())
},
);
let pipeline = service.pipeline(());
assert_eq!(pipeline.call("41").await?, "42");See the framework guide’s Service Pipelines chapter for composition and readiness semantics.