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:
AttemptWorkerContextData<T>where T is injected viatask.data(...)TaskId
§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§
- From
Request - A trait for extracting types from a task’s context.