diff --git a/src/db/models/plant.rs b/src/db/models/plant.rs index 205a847..7dfa583 100644 --- a/src/db/models/plant.rs +++ b/src/db/models/plant.rs @@ -1,7 +1,7 @@ use diesel::prelude::*; use serde::{Deserialize, Serialize}; -use crate::db::{schema::*, DbPool, DbResult}; +use crate::db::{schema::*, DbPool, DbResult, Pagination}; #[derive(Serialize, Queryable, Selectable)] #[diesel(table_name = plants)] @@ -45,4 +45,12 @@ impl Plant { .first(&mut pool.get()?) .optional()?) } + + pub fn page(pool: &DbPool, page: Pagination) -> DbResult> { + Ok(plants::table + .select(Self::as_select()) + .offset((page.page * page.per_page).into()) + .limit(page.per_page.into()) + .get_results(&mut pool.get()?)?) + } } diff --git a/src/server/plants.rs b/src/server/plants.rs index d983baf..4e7df3a 100644 --- a/src/server/plants.rs +++ b/src/server/plants.rs @@ -1,20 +1,20 @@ use axum::{ - extract::{Path, State}, + extract::{Path, Query, State}, http::HeaderMap, response::Html, - routing::{get, post}, + routing::get, Form, Router, }; use tera::Context; -use crate::db::{self, DbError, Event, Plant}; +use crate::db::{self, DbError, Event, Pagination, Plant}; use super::error::AppError; pub fn app() -> axum::Router { Router::new() .route("/{id}", get(get_plant_page)) - .route("/", post(post_plant)) + .route("/", get(get_plants).post(post_plant)) } async fn get_plant_page( @@ -54,6 +54,26 @@ async fn get_plant_page( } } +async fn get_plants( + State(ctx): State, + Query(page): Query, + headers: HeaderMap, +) -> super::Result> { + let plants = tokio::task::spawn_blocking(move || db::Plant::page(&ctx.pool, page)) + .await + .unwrap()?; + + let mut context = Context::new(); + context.insert("plants", &plants); + + Ok(Html(super::render_view( + &ctx.tera, + "views/plants.html", + &context, + &headers, + )?)) +} + async fn post_plant( State(ctx): State, Form(plant): Form, diff --git a/templates/components/plant.html b/templates/components/plant.html index a654bb5..d68e6b5 100644 --- a/templates/components/plant.html +++ b/templates/components/plant.html @@ -8,9 +8,13 @@ {% endmacro info %} +{% macro name(plant) %} +{{ plant.name }} ({{ plant.species }}) +{% endmacro %} + {% macro li(plant) %}
  • - {{ plant.name }} ({{ plant.species }}) + {{ self::name(plant=plant) }}
  • {% endmacro li %} @@ -26,16 +30,9 @@ {% macro form(target="#plants > ul") %}
    - -
    - -
    - -
    - +
    +
    +
    +
    {% endmacro %} - -{% macro name(plant) %} -{{ plant.name }} ({{ plant.species }}) -{% endmacro %} diff --git a/templates/views/plants.html b/templates/views/plants.html new file mode 100644 index 0000000..22d4aa6 --- /dev/null +++ b/templates/views/plants.html @@ -0,0 +1,9 @@ +{% import "components/plant.html" as comp_plant %} + +

    Plants

    + +
      +{% for plant in plants %} + {{ comp_plant::li(plant=plant) }} +{% endfor %} +