From 66254d63bd55562b0010c40c481fd71abb652eeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Coletta?= Date: Wed, 29 May 2024 11:06:13 +0200 Subject: [PATCH] chore: Add app state documentation in README --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/README.md b/README.md index 73dc645..32226ae 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,55 @@ async fn main() -> Result<(), ()> { } ``` +### App state + +You can provide app state through `extension` : + +```rust,ignore +use serde::{Deserialize, Serialize}; +use graphile_worker::{WorkerContext, TaskHandler}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; +use std::sync::Arc; + +#[derive(Clone, Debug)] +struct AppState { + run_count: Arc, +} + +#[derive(Deserialize, Serialize)] +pub struct CounterTask; + +impl TaskHandler for CounterTask { + const IDENTIFIER: &'static str = "counter_task"; + + async fn run(self, _ctx: WorkerContext) -> Result<(), ()> { + let app_state = ctx.extensions().get::().unwrap(); + let run_count = app_state.run_count.fetch_add(1, SeqCst); + println!("Run count: {run_count}"); + Ok(()) + } +} + +#[tokio::main] +async fn main() -> Result<(), ()> { + graphile_worker::WorkerOptions::default() + .concurrency(2) + .schema("example_simple_worker") + .add_extension(AppState { + run_count: Arc::new(AtomicUsize::new(0)), + }) + .define_job::() + .pg_pool(pg_pool) + .init() + .await? + .run() + .await?; + + Ok(()) +} +``` + ### Success! You should see the worker output `Hello Bobby Tables !`. Gosh, that was fast!