Struct State

Source
pub struct State<T>(pub T);
Expand description

Extract shared application state

This extractor provides access to the shared application state that was provided when creating the router. The state is automatically cloned for each request, avoiding the need to manage Arc<Mutex<T>> manually.

§Database Connection Patterns

The state system is designed to work seamlessly with database connection pools. Since state is cloned for each request, database connections should use connection pools wrapped in Arc for efficient sharing.

§PostgreSQL Example (using sqlx)

use coapum::extract::State;
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    db: Arc<sqlx::PgPool>,
    cache: Arc<tokio::sync::RwLock<std::collections::HashMap<String, String>>>,
}

async fn get_user_handler(State(state): State<AppState>) -> Result<String, Box<dyn std::error::Error>> {
    let user = sqlx::query!("SELECT name FROM users WHERE id = $1", 1)
        .fetch_one(&*state.db)
        .await?;
    Ok(user.name)
}

§SQLite Example (using sqlx)

use coapum::{Json, extract::State};
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    db: Arc<sqlx::SqlitePool>,
    config: AppConfig,
}

async fn insert_data_handler(
    State(state): State<AppState>,
    Json(data): Json<serde_json::Value>
) -> Result<(), Box<dyn std::error::Error>> {
    sqlx::query!("INSERT INTO data (payload) VALUES (?)", data.to_string())
        .execute(&*state.db)
        .await?;
    Ok(())
}

§Diesel Example

use coapum::extract::State;
use std::sync::Arc;
use diesel::r2d2::{Pool, ConnectionManager};
use diesel::PgConnection;

type DbPool = Arc<Pool<ConnectionManager<PgConnection>>>;

#[derive(Clone)]
struct AppState {
    db_pool: DbPool,
    redis_client: Arc<redis::Client>,
}

async fn database_handler(State(state): State<AppState>) {
    let mut conn = state.db_pool.get().expect("Failed to get connection");
    // Use connection for database operations
}

§Generic Database Pattern

For maximum flexibility, you can define a trait for database operations:

use async_trait::async_trait;
use coapum::extract::State;
use std::sync::Arc;

#[derive(Clone)]
struct User {
    id: i32,
    name: String,
}

#[derive(Clone)]
struct Cache {
    // Cache implementation
}

#[async_trait]
pub trait DatabaseOps: Send + Sync + Clone {
    type Error: std::error::Error + Send + Sync + 'static;
     
    async fn get_user(&self, id: i32) -> Result<User, Self::Error>;
    async fn save_data(&self, data: &serde_json::Value) -> Result<(), Self::Error>;
}

#[derive(Clone)]
struct AppState<DB: DatabaseOps> {
    db: DB,
    cache: Arc<tokio::sync::RwLock<Cache>>,
}

async fn generic_handler<DB: DatabaseOps>(
    State(state): State<AppState<DB>>
) -> Result<(), DB::Error> {
    let user = state.db.get_user(123).await?;
    Ok(())
}

§Best Practices for State Management

  1. Use Arc for shared resources: Database pools, configuration, caches
  2. Keep state lightweight: Large objects should be behind Arc
  3. Prefer connection pools: For database connections, always use pools
  4. Clone should be cheap: State is cloned per request, so make it efficient
  5. Consider read-heavy workloads: Use Arc<RwLock<T>> for cached data that’s read frequently

§Basic Example

use coapum::extract::State;

#[derive(Clone)]
struct AppState {
    database_url: String,
    api_key: String,
}

async fn handle_with_state(State(state): State<AppState>) {
    println!("Database: {}", state.database_url);
}

Tuple Fields§

§0: T

Trait Implementations§

Source§

impl<T> Clone for State<T>
where T: Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for State<T>
where T: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Deref for State<T>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<T> DerefMut for State<T>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<T, S> FromRequest<S> for State<T>
where T: Clone + Send + Sync + 'static, S: AsRef<T> + Send + Sync,

Source§

type Rejection = StateRejection

The error type returned when extraction fails
Source§

fn from_request<'life0, 'life1, 'async_trait>( _req: &'life0 CoapumRequest<SocketAddr>, state: &'life1 S, ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Extract this type from the request

Auto Trait Implementations§

§

impl<T> Freeze for State<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for State<T>
where T: RefUnwindSafe,

§

impl<T> Send for State<T>
where T: Send,

§

impl<T> Sync for State<T>
where T: Sync,

§

impl<T> Unpin for State<T>
where T: Unpin,

§

impl<T> UnwindSafe for State<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,

Source§

impl<T> Parsable for T
where T: Deref, <T as Deref>::Target: Parsable,