From 8d8857cacee75fa4041cd66481221ceb9ea1e7a6 Mon Sep 17 00:00:00 2001 From: itsscb Date: Sun, 25 May 2025 22:27:26 +0200 Subject: [PATCH] feat: add script details route --- src/router.rs | 3 +- src/router/routes/scripts.rs | 59 +++++++++++++++++++++++++++++++----- 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/router.rs b/src/router.rs index 13e388b..4771183 100644 --- a/src/router.rs +++ b/src/router.rs @@ -1,5 +1,5 @@ use axum::routing::{get, get_service}; -use routes::scripts::get_scripts; +use routes::scripts::{get_script_by_id, get_scripts}; use sqlx::SqlitePool; use tower_http::services::ServeDir; mod routes; @@ -8,5 +8,6 @@ pub fn new_router(db: SqlitePool) -> axum::Router { axum::Router::new() .fallback_service(get_service(ServeDir::new("assets"))) .route("/scripts", get(get_scripts)) + .route("/scripts/{id}", get(get_script_by_id)) .with_state(db) } diff --git a/src/router/routes/scripts.rs b/src/router/routes/scripts.rs index 5a58349..8c94c60 100644 --- a/src/router/routes/scripts.rs +++ b/src/router/routes/scripts.rs @@ -1,11 +1,45 @@ use axum::{ - extract::State, + extract::{Path, State}, http::StatusCode, response::{Html, IntoResponse}, }; use sqlx::SqlitePool; use std::fmt::Write; -use tracing::{error, instrument}; +use tracing::{error, instrument, warn}; + +#[instrument(skip_all)] +pub async fn get_script_by_id( + State(database): State, + Path(id): Path, +) -> impl IntoResponse { + let script = match crate::db::get_script(&database, id).await { + Ok(script) => script, + Err(e) => { + warn!(err = e.to_string(), "get_script"); + return Err(StatusCode::NOT_FOUND); + } + }; + + let output = format!( + r##"

{}

{}
"##, + script.0, + script.1.name(), + script.0, + script + .1 + .parameters() + .iter() + .fold(String::new(), |mut acc, x| { + if let Err(e) = write!(acc, "

{:?}

", x) { + error!(err = e.to_string(), script = ?x, "failed to write parameter"); + return String::new(); + } + acc + }) + ); + + Ok(Html(output)) +} #[instrument(skip_all)] pub async fn get_scripts(State(database): State) -> impl IntoResponse { @@ -18,14 +52,23 @@ pub async fn get_scripts(State(database): State) -> impl IntoRespons }; let content = scripts.iter().fold(String::new(), |mut acc, x| { - if let Err(e) = write!(acc, "
  • {} [", x.1.name()) { - error!(err = e.to_string(), script=?x ,"failed to write name"); - return String::new(); - } - if let Err(e) = write!(acc, "{}]
  • ", x.0) { - error!(err = e.to_string(), script=?x ,"failed to write id"); + if let Err(e) = write!( + acc, + r##"
  • {1} [{0}]
  • "##, + x.0, + x.1.name() + ) { + error!(err = e.to_string(), script=?x ,"failed to write script"); return String::new(); } + // if let Err(e) = write!(acc, "{} [", x.1.name()) { + // error!(err = e.to_string(), script=?x ,"failed to write id"); + // return String::new(); + // } + // if let Err(e) = write!(acc, "{}]", x.0) { + // error!(err = e.to_string(), script=?x ,"failed to write id"); + // return String::new(); + // } acc });