simple-web-app

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

state.rs (1009B)


      1 use std::sync::Arc;
      2 
      3 use crate::config::Config;
      4 use crate::database::Database;
      5 
      6 #[derive(Clone)]
      7 pub struct AppState {
      8     pub config: Arc<Config>,
      9     pub db: Arc<Database>,
     10     pub comment_tx: tokio::sync::broadcast::Sender<i64>,
     11 }
     12 
     13 impl AppState {
     14     pub fn new(config: Config, db: Database) -> Self {
     15         let (comment_tx, _) = tokio::sync::broadcast::channel(64);
     16         Self {
     17             config: Arc::new(config),
     18             db: Arc::new(db),
     19             comment_tx,
     20         }
     21     }
     22 
     23     /// Look up session token in DB, return user_id if valid.
     24     pub async fn get_user_id(&self, jar: &axum_extra::extract::cookie::CookieJar) -> Option<i64> {
     25         let token = crate::handlers::auth::get_session_token(jar)?;
     26         self.db.get_session_user_id(&token).await.ok().flatten()
     27     }
     28 
     29     /// Access the database. Reads/writes dispatch to dedicated thread
     30     /// pools and return via tokio oneshot — fully async, no spawn_blocking.
     31     pub fn db(&self) -> &Database {
     32         &self.db
     33     }
     34 }