feat: add sqlx transaction extractor to router

This commit is contained in:
Alexander Navarro 2025-02-22 18:54:44 -03:00
parent cfaf7ecc1f
commit a662b94b21
8 changed files with 79 additions and 14 deletions

View file

@ -1,12 +1,13 @@
mod error;
pub mod router;
use axum::extract::FromRef;
pub use error::{Error, Result, ResultTemplate};
use minijinja::{Environment, Template};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
pub type Tx = axum_sqlx_tx::Tx<sqlx::Postgres>;
pub type TxState = axum_sqlx_tx::State<sqlx::Postgres>;
#[derive(Serialize, Deserialize, Debug)]
pub struct Link {
@ -15,13 +16,15 @@ pub struct Link {
pub subpages: Vec<Self>,
}
#[derive(Clone, FromRef)]
pub struct AppState {
tmpl_env: Environment<'static>,
tx: TxState,
}
impl AppState {
pub fn new(tmpl_env: Environment<'static>) -> Arc<Self> {
Arc::new(AppState { tmpl_env })
pub fn new(tmpl_env: Environment<'static>, tx: TxState) -> Self {
AppState { tmpl_env, tx }
}
pub fn get_template(&self, name: &str) -> Result<Template> {

View file

@ -77,9 +77,8 @@ async fn main() -> Result<()> {
let app = router::new()
.layer(TraceLayer::new_for_http().on_request(()))
.with_state(AppState::new(tmpl_env))
.layer(tx_layer)
.with_state(tx_state);
.with_state(AppState::new(tmpl_env, tx_state));
// Add hot reload only on dev mode
#[cfg(debug_assertions)]

View file

@ -1,20 +1,37 @@
use axum::{extract::State, response::Html, routing::get, Router};
use chrono::Utc;
use minijinja::context;
use std::sync::Arc;
use serde::Serialize;
use sqlx::prelude::FromRow;
use tower_http::services::ServeDir;
use crate::{AppState, ResultTemplate};
use crate::{AppState, ResultTemplate, Tx};
pub fn new() -> Router<Arc<AppState>> {
pub fn new() -> Router<AppState> {
Router::new()
.route("/", get(handler_home))
.nest_service("/assets", ServeDir::new("dist/assets"))
}
async fn handler_home(State(state): State<Arc<AppState>>) -> ResultTemplate {
let template = state.tmpl_env.get_template("base.html")?;
#[derive(FromRow, Debug, Serialize)]
struct ExampleRow {
pub database: String,
pub version: String,
pub current_database: String,
pub current_user: String,
pub current_timestamp: chrono::DateTime<Utc>,
}
let content = template.render(context!())?;
async fn handler_home(State(state): State<AppState>, mut tx: Tx) -> ResultTemplate {
let template = state.tmpl_env.get_template("index.html")?;
let rows = sqlx::query_as::<_, ExampleRow>("select 'Postgres' as database, setting as version, current_database(), current_user, current_timestamp from pg_settings where name = 'server_version'")
.fetch_all(&mut tx)
.await?;
println!("{:?}", rows);
let content = template.render(context!(rows => rows))?;
Ok(Html(content))
}