refactor: move db stuff into own module
This commit is contained in:
parent
412f4cd2c7
commit
f96bf4d193
5 changed files with 111 additions and 66 deletions
|
|
@ -4,30 +4,9 @@ use axum::{
|
|||
routing::{get, post},
|
||||
Form, Router,
|
||||
};
|
||||
use r2d2_sqlite::rusqlite::{self, Row};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tera::Context;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Plant {
|
||||
id: i32,
|
||||
name: String,
|
||||
species: String,
|
||||
description: 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)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
use crate::db;
|
||||
|
||||
pub fn app(ctx: crate::Context) -> axum::Router {
|
||||
let mut router = Router::new()
|
||||
|
|
@ -42,55 +21,24 @@ pub fn app(ctx: crate::Context) -> axum::Router {
|
|||
}
|
||||
|
||||
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 plants = tokio::task::spawn_blocking(move || db::list_plants(&ctx.pool))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let mut context = Context::new();
|
||||
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>,
|
||||
Form(plant): Form<db::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 plant = tokio::task::spawn_blocking(move || db::insert_plant(&ctx.pool, &plant))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let mut context = Context::new();
|
||||
context.insert("plant", &plant);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue