full functionality

This commit is contained in:
Khaïs COLIN 2025-10-18 22:12:51 +02:00
parent bc4203aee0
commit fc64df2b2a
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo
3 changed files with 41 additions and 7 deletions

View file

@ -1,6 +1,6 @@
use std::sync::{Arc, Mutex};
use axum::{extract::State, response::Html, routing::get, Router};
use axum::{extract::{Path, State}, response::{Html, Redirect}, routing::{get, post}, Router};
use rusqlite::Connection;
use askama::Template;
@ -8,6 +8,7 @@ use askama::Template;
#[template(path = "index.html")]
struct IndexTemplate {
foods: Vec<Food>,
sum: i32,
}
#[derive(Debug, Clone, PartialEq)]
@ -27,7 +28,10 @@ async fn main() {
conn.execute(include_str!("create_tables.sql"), ()).unwrap();
let conn = Arc::new(Mutex::new(conn));
let app = Router::new().route("/", get(root)).with_state(conn);
let app = Router::new().route("/", get(root))
.route("/increase/{id}", post(increase))
.route("/decrease/{id}", post(decrease))
.with_state(conn);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
@ -49,8 +53,29 @@ async fn root(
actual_servings: row.get(5).unwrap(),
})
}).unwrap().collect::<Result<_, _>>().unwrap();
let index = IndexTemplate {foods};
let mut stmt = conn.prepare("SELECT SUM(kc_per_serving * actual_servings) as kc FROM food").unwrap();
let sum = stmt.query_one((), |row| row.get(0)).unwrap();
let index = IndexTemplate {foods, sum};
Html(
index.render().unwrap()
)
}
async fn increase(
State(conn): State<Arc<Mutex<Connection>>>,
Path(id): Path<i32>
) -> Redirect{
let conn = conn.lock().unwrap();
let mut stmt = conn.prepare("UPDATE food SET actual_servings = (SELECT actual_servings FROM food WHERE id = ?1) + 1 WHERE id = ?1").unwrap();
stmt.execute((id,)).unwrap();
Redirect::to("/")
}
async fn decrease(
State(conn): State<Arc<Mutex<Connection>>>,
Path(id): Path<i32>
) -> Redirect{
let conn = conn.lock().unwrap();
let mut stmt = conn.prepare("UPDATE food SET actual_servings = (SELECT actual_servings FROM food WHERE id = ?1) - 1 WHERE id = ?1").unwrap();
stmt.execute((id,)).unwrap();
Redirect::to("/")
}