Skip to main content

FromDependencyWithCleanup

Trait FromDependencyWithCleanup 

Source
pub trait FromDependencyWithCleanup:
    Clone
    + Send
    + Sync
    + 'static {
    type Value: Clone + Send + Sync + 'static;
    type Error: IntoResponse + Send + Sync + 'static;

    // Required method
    fn setup(
        ctx: &RequestContext,
        req: &mut Request,
    ) -> impl Future<Output = Result<(Self::Value, Option<CleanupFn>), Self::Error>> + Send;
}
Expand description

Trait for dependencies that require cleanup after handler completion.

This is similar to FastAPI’s yield dependencies. Dependencies implementing this trait can perform setup logic and register cleanup functions that run after the request handler completes.

§Example

struct DbTransaction {
    tx: Transaction,
}

impl FromDependencyWithCleanup for DbTransaction {
    type Value = DbTransaction;
    type Error = HttpError;

    async fn setup(ctx: &RequestContext, req: &mut Request)
        -> Result<(Self::Value, Option<CleanupFn>), Self::Error>
    {
        let pool = Depends::<DbPool>::from_request(ctx, req).await?;
        let tx = pool.begin().await.map_err(|_| HttpError::internal())?;

        let cleanup_tx = tx.clone();
        let cleanup = Box::new(move || {
            Box::pin(async move {
                // Commit or rollback happens here
                cleanup_tx.commit().await.ok();
            }) as Pin<Box<dyn Future<Output = ()> + Send>>
        }) as CleanupFn;

        Ok((DbTransaction { tx }, Some(cleanup)))
    }
}

Required Associated Types§

Source

type Value: Clone + Send + Sync + 'static

The value type produced by setup.

Source

type Error: IntoResponse + Send + Sync + 'static

Error type when setup fails.

Required Methods§

Source

fn setup( ctx: &RequestContext, req: &mut Request, ) -> impl Future<Output = Result<(Self::Value, Option<CleanupFn>), Self::Error>> + Send

Set up the dependency and optionally return a cleanup function.

The cleanup function (if provided) will run after the request handler completes, even on error or panic.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§