wrap

Attribute Macro wrap 

#[wrap]
Expand description

Define a wrapping middleware.

§Example

A middleware that applies a timeout to all incoming requests:

use pavex::{wrap, middleware::Next, Response};
use tokio::time::error::Elapsed;

#[wrap]
pub async fn timeout<C>(next: Next<C>) -> Result<Response, Elapsed>
where
    C: IntoFuture<Output = Response>,
{
    let max_duration = std::time::Duration::from_secs(20);
    tokio::time::timeout(max_duration, next.into_future()).await
}

§Guide

Check out the “Middlewares” section of Pavex’s guide for a thorough introduction to middlewares in Pavex applications.

§Registration

Use Blueprint::wrap to register the middleware with your Blueprint.

The #[wrap] macro generates a constant that you can use to refer to the middleware when invoking Blueprint::wrap.

§Arguments

The sections below provide an exhaustive list of all the arguments and flags supported by the wrap macro:

NameKindRequired
idArgumentNo

§id

By default, Pavex generates a constant named after your function (converted to UPPER_SNAKE_CASE) that you use when registering the middleware.

The id argument allows you to customize the name of the generated constant.

§Example

Using the default generated identifier:

use pavex::{wrap, Blueprint, middleware::Next, Response};
use tokio::time::error::Elapsed;

#[wrap]
pub async fn timeout<C>(next: Next<C>) -> Result<Response, Elapsed>
where
    C: IntoFuture<Output = Response>,
{
    let max_duration = std::time::Duration::from_secs(20);
    tokio::time::timeout(max_duration, next.into_future()).await
}

let mut bp = Blueprint::new();
bp.wrap(TIMEOUT);

Using a custom identifier:

use pavex::{wrap, Blueprint, middleware::Next, Response};
use tokio::time::error::Elapsed;

#[wrap(id = "MY_TIMEOUT")]
//     👆 Custom identifier
pub async fn timeout<C>(next: Next<C>) -> Result<Response, Elapsed>
where
    C: IntoFuture<Output = Response>,
{
    let max_duration = std::time::Duration::from_secs(20);
    tokio::time::timeout(max_duration, next.into_future()).await
}

let mut bp = Blueprint::new();
// Use the custom identifier when registering
bp.wrap(MY_TIMEOUT);