81 lines
2.5 KiB
Rust
81 lines
2.5 KiB
Rust
use axum::{
|
|
extract::{Path, State},
|
|
http::StatusCode,
|
|
response::{Html, IntoResponse},
|
|
};
|
|
use sqlx::SqlitePool;
|
|
use std::fmt::Write;
|
|
use tracing::{error, instrument, warn};
|
|
|
|
#[instrument(skip_all)]
|
|
pub async fn get_script_by_id(
|
|
State(database): State<SqlitePool>,
|
|
Path(id): Path<String>,
|
|
) -> 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##"<section id="{}"><h1>{}</h1><div id="{}-parameters">{}</div></section>"##,
|
|
script.0,
|
|
script.1.name(),
|
|
script.0,
|
|
script
|
|
.1
|
|
.parameters()
|
|
.iter()
|
|
.fold(String::new(), |mut acc, x| {
|
|
if let Err(e) = write!(acc, "<p>{:?}</p>", 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<SqlitePool>) -> impl IntoResponse {
|
|
let scripts = match crate::db::list_scripts(&database).await {
|
|
Ok(scripts) => scripts,
|
|
Err(e) => {
|
|
error!(err = e, "list_scripts");
|
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
|
}
|
|
};
|
|
|
|
let content = scripts.iter().fold(String::new(), |mut acc, x| {
|
|
if let Err(e) = write!(
|
|
acc,
|
|
r##"<li hx-get="/scripts/{0}" hx-push-url="/scripts/{0}" hx-target="#scripts" hx-swap="outerHTML">{1} [{0}]</li>"##,
|
|
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, "{}]</li>", x.0) {
|
|
// error!(err = e.to_string(), script=?x ,"failed to write id");
|
|
// return String::new();
|
|
// }
|
|
acc
|
|
});
|
|
|
|
let output = format!(
|
|
r##"<section id="scripts"><ul>{content}</ul><button hx-get="/scripts" hx-swap="outerHTML" hx-target="#scripts">Refresh</button></section>"##
|
|
);
|
|
|
|
Ok(Html(output))
|
|
}
|