feat: playing with htmx
This commit is contained in:
parent
08f6faef52
commit
35f1433e40
8 changed files with 88 additions and 14 deletions
|
|
@ -1,6 +1,11 @@
|
|||
use axum::{extract::State, response::Html, routing::get, Router};
|
||||
use axum::{
|
||||
extract::State,
|
||||
response::Html,
|
||||
routing::{get, post},
|
||||
Form, Router,
|
||||
};
|
||||
use r2d2_sqlite::rusqlite::{self, Row};
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tera::Context;
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -8,7 +13,7 @@ struct Plant {
|
|||
id: i32,
|
||||
name: String,
|
||||
species: String,
|
||||
description: Option<String>,
|
||||
description: String,
|
||||
}
|
||||
|
||||
impl TryFrom<&Row<'_>> for Plant {
|
||||
|
|
@ -25,7 +30,10 @@ impl TryFrom<&Row<'_>> for Plant {
|
|||
}
|
||||
|
||||
pub fn app(ctx: crate::Context) -> axum::Router {
|
||||
Router::new().route("/", get(get_index)).with_state(ctx)
|
||||
Router::new()
|
||||
.route("/", get(get_index))
|
||||
.route("/plants", post(post_plants))
|
||||
.with_state(ctx)
|
||||
}
|
||||
|
||||
async fn get_index(State(ctx): State<crate::Context>) -> Html<String> {
|
||||
|
|
@ -48,3 +56,38 @@ async fn get_index(State(ctx): State<crate::Context>) -> Html<String> {
|
|||
context.insert("plants", &plants);
|
||||
Html(ctx.tera.render("index.html", &context).unwrap())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct NewPlant {
|
||||
name: String,
|
||||
species: String,
|
||||
description: String,
|
||||
}
|
||||
|
||||
async fn post_plants(
|
||||
State(ctx): State<crate::Context>,
|
||||
Form(plant): Form<NewPlant>,
|
||||
) -> Html<String> {
|
||||
let plant = tokio::task::spawn_blocking(move || {
|
||||
let conn = ctx.pool.get().unwrap();
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"insert into plants (name, species, description) values ($1, $2, $3) returning *",
|
||||
)
|
||||
.unwrap();
|
||||
let plant = stmt
|
||||
.query_row((&plant.name, &plant.species, &plant.description), |row| {
|
||||
Plant::try_from(row)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
plant
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut context = Context::new();
|
||||
context.insert("plant", &plant);
|
||||
Html(ctx.tera.render("plant_li.html", &context).unwrap())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue