feat: initial page rendering; db stuff
This commit is contained in:
parent
a410e4f9ec
commit
08f6faef52
7 changed files with 692 additions and 23 deletions
50
src/server/mod.rs
Normal file
50
src/server/mod.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
use axum::{extract::State, response::Html, routing::get, Router};
|
||||
use r2d2_sqlite::rusqlite::{self, Row};
|
||||
use serde::Serialize;
|
||||
use tera::Context;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Plant {
|
||||
id: i32,
|
||||
name: String,
|
||||
species: String,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
impl TryFrom<&Row<'_>> for Plant {
|
||||
type Error = rusqlite::Error;
|
||||
|
||||
fn try_from(row: &Row<'_>) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
species: row.get(2)?,
|
||||
description: row.get(3)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn app(ctx: crate::Context) -> axum::Router {
|
||||
Router::new().route("/", get(get_index)).with_state(ctx)
|
||||
}
|
||||
|
||||
async fn get_index(State(ctx): State<crate::Context>) -> Html<String> {
|
||||
let plants = tokio::task::spawn_blocking(move || {
|
||||
let conn = ctx.pool.get().unwrap();
|
||||
|
||||
let mut stmt = conn.prepare("select * from plants").unwrap();
|
||||
let mut plants = Vec::new();
|
||||
|
||||
for plant in stmt.query_map((), |row| Plant::try_from(row)).unwrap() {
|
||||
plants.push(plant.unwrap());
|
||||
}
|
||||
|
||||
plants
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut context = Context::new();
|
||||
context.insert("plants", &plants);
|
||||
Html(ctx.tera.render("index.html", &context).unwrap())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue