Set up global app state

This commit is contained in:
Joscha 2023-08-04 14:21:20 +02:00
parent 4028c3eea2
commit 037f076475
2 changed files with 22 additions and 8 deletions

View file

@ -1,10 +1,11 @@
mod db; mod state;
mod r#static; mod r#static;
use askama::Template; use askama::Template;
use askama_axum::{IntoResponse, Response}; 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 sqlx::SqlitePool;
use state::AppState;
#[derive(Template)] #[derive(Template)]
#[template(path = "index.html")] #[template(path = "index.html")]
@ -12,9 +13,9 @@ struct IndexTemplate {
number: i32, number: i32,
} }
async fn index(Extension(pool): Extension<SqlitePool>) -> Result<Response, Response> { async fn index(State(db): State<SqlitePool>) -> Result<Response, Response> {
let result = sqlx::query!("SELECT column1 AS number FROM (VALUES (1))") let result = sqlx::query!("SELECT column1 AS number FROM (VALUES (1))")
.fetch_one(&pool) .fetch_one(&db)
.await .await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")).into_response())?; .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")).into_response())?;
@ -23,12 +24,12 @@ async fn index(Extension(pool): Extension<SqlitePool>) -> Result<Response, Respo
} }
async fn run() -> anyhow::Result<()> { async fn run() -> anyhow::Result<()> {
let pool = db::pool().await?; let state = AppState::new().await?;
let app = Router::new() let app = Router::new()
.route("/", get(index)) .route("/", get(index))
.fallback(get(r#static::static_handler)) .fallback(get(r#static::static_handler))
.layer(Extension(pool)); .with_state(state);
// TODO Add text body to body-less status codes // TODO Add text body to body-less status codes
axum::Server::bind(&"0.0.0.0:8000".parse().unwrap()) axum::Server::bind(&"0.0.0.0:8000".parse().unwrap())

View file

@ -1,12 +1,14 @@
// TODO Occasionally run PRAGMA optimize //! Globally accessible application state.
use axum::extract::FromRef;
use sqlx::{ use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous}, sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
SqlitePool, SqlitePool,
}; };
// TODO Occasionally run PRAGMA optimize
// TODO Open db from path // TODO Open db from path
pub async fn pool() -> sqlx::Result<SqlitePool> { async fn pool() -> sqlx::Result<SqlitePool> {
let options = SqliteConnectOptions::new() let options = SqliteConnectOptions::new()
// https://www.sqlite.org/pragma.html#pragma_journal_mode // https://www.sqlite.org/pragma.html#pragma_journal_mode
.journal_mode(SqliteJournalMode::Wal) .journal_mode(SqliteJournalMode::Wal)
@ -27,3 +29,14 @@ pub async fn pool() -> sqlx::Result<SqlitePool> {
Ok(pool) Ok(pool)
} }
#[derive(Clone, FromRef)]
pub struct AppState {
pub db: SqlitePool,
}
impl AppState {
pub async fn new() -> anyhow::Result<Self> {
Ok(Self { db: pool().await? })
}
}