generated from alecodes/base-template
77 lines
1.7 KiB
Rust
77 lines
1.7 KiB
Rust
use crate::config::Config;
|
|
use crate::{AppState, ResultTemplate, Tx};
|
|
use axum::{
|
|
extract::State
|
|
,
|
|
routing::get,
|
|
Router,
|
|
};
|
|
use axum_htmx::HxRequest;
|
|
use chrono::Utc;
|
|
use minijinja::context;
|
|
use serde::Serialize;
|
|
use sqlx::prelude::FromRow;
|
|
use tower_http::services::ServeDir;
|
|
|
|
pub fn new(config: &Config) -> Router<AppState> {
|
|
let router = Router::new()
|
|
.route("/", get(handler_home))
|
|
.nest("/public", load_asset_router(config));
|
|
|
|
router
|
|
}
|
|
|
|
#[cfg(feature = "embed")]
|
|
fn load_asset_router(config: &Config) -> Router<AppState> {
|
|
Router::new()
|
|
.fallback_service(
|
|
ServeDir::new(&config.public_dir),
|
|
)
|
|
.nest_service(
|
|
"/assets",
|
|
ServeDir::new(concat!(env!("OUT_DIR"), "/assets")),
|
|
)
|
|
}
|
|
|
|
#[cfg(not(feature = "embed"))]
|
|
fn load_asset_router(config: &Config) -> Router<AppState> {
|
|
Router::new()
|
|
.fallback_service(
|
|
ServeDir::new(&config.public_dir),
|
|
)
|
|
.nest_service(
|
|
"/assets",
|
|
ServeDir::new(&config.public_dir.join("assets")),
|
|
)
|
|
}
|
|
|
|
#[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>,
|
|
}
|
|
|
|
async fn handler_home(
|
|
State(state): State<AppState>,
|
|
HxRequest(hx_request): HxRequest,
|
|
mut tx: Tx,
|
|
) -> ResultTemplate {
|
|
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?;
|
|
|
|
let content = if hx_request {
|
|
state
|
|
.assets
|
|
.render_template_block("index.html", "htmx", context!(rows => rows))?
|
|
} else {
|
|
state
|
|
.assets
|
|
.render_template("index.html", context!(rows => rows))?
|
|
};
|
|
|
|
Ok(content)
|
|
}
|