Skip to main content

Module from_request

Module from_request 

Source
Expand description

Traits for offering dependency injection in task functions.

This allows for more ergonomic access to common types within the task context. Items have this already implemented:

§Example

Say we have a basic task for sending emails given the user id

struct Email {
    user_id: String,
    subject: String,
    message: String
}
async fn send_email_by_id(email: Email) -> Result<(), BoxDynError> {
    let user_id = email.user_id;
    let user = User::find_by_id(user_id).await?;
    // Do something with user

    Ok(())
}

With FromRequest you can improve the experience by:

impl FromRequest<Task<Email>> for User {
    type Error = BoxDynError;
    async fn from_request(req: &Task<Email>) -> Result<Self, BoxDynError> {
        let user_id = &req.args.user_id;
        let user = User::find_by_id(user_id).await?;
        Ok(user)
    }
}

async fn send_email(email: Email, user: User) -> Result<(), BoxDynError> {
    // Do something with user
    Ok(())
}

Traits§

FromRequest
A trait for extracting types from a task’s context.