diff --git a/src/main.rs b/src/main.rs index f216e11..2532ef0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ -mod db; +mod state; mod r#static; use askama::Template; use askama_axum::{IntoResponse, Response}; -use axum::{http::StatusCode, routing::get, Extension, Router}; +use axum::{extract::State, http::StatusCode, routing::get, Router}; use sqlx::SqlitePool; +use state::AppState; #[derive(Template)] #[template(path = "index.html")] @@ -12,9 +13,9 @@ struct IndexTemplate { number: i32, } -async fn index(Extension(pool): Extension) -> Result { +async fn index(State(db): State) -> Result { let result = sqlx::query!("SELECT column1 AS number FROM (VALUES (1))") - .fetch_one(&pool) + .fetch_one(&db) .await .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")).into_response())?; @@ -23,12 +24,12 @@ async fn index(Extension(pool): Extension) -> Result anyhow::Result<()> { - let pool = db::pool().await?; + let state = AppState::new().await?; let app = Router::new() .route("/", get(index)) .fallback(get(r#static::static_handler)) - .layer(Extension(pool)); + .with_state(state); // TODO Add text body to body-less status codes axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()) diff --git a/src/db.rs b/src/state.rs similarity index 76% rename from src/db.rs rename to src/state.rs index 8c46eb0..5cecb40 100644 --- a/src/db.rs +++ b/src/state.rs @@ -1,12 +1,14 @@ -// TODO Occasionally run PRAGMA optimize +//! Globally accessible application state. +use axum::extract::FromRef; use sqlx::{ sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous}, SqlitePool, }; +// TODO Occasionally run PRAGMA optimize // TODO Open db from path -pub async fn pool() -> sqlx::Result { +async fn pool() -> sqlx::Result { let options = SqliteConnectOptions::new() // https://www.sqlite.org/pragma.html#pragma_journal_mode .journal_mode(SqliteJournalMode::Wal) @@ -27,3 +29,14 @@ pub async fn pool() -> sqlx::Result { Ok(pool) } + +#[derive(Clone, FromRef)] +pub struct AppState { + pub db: SqlitePool, +} + +impl AppState { + pub async fn new() -> anyhow::Result { + Ok(Self { db: pool().await? }) + } +}