Load more button on Posts page
Some checks failed
Rust / Test (push) Has been cancelled
Rust / Rustfmt (push) Has been cancelled
Rust / Clippy (push) Has been cancelled
Rust / Code coverage (push) Has been cancelled

This commit is contained in:
Alphonse Paix
2025-09-23 18:24:12 +02:00
parent 5c5e3b0e4c
commit b1e315921e
7 changed files with 96 additions and 37 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,3 @@
use crate::templates::PostCardTemplate;
use askama::Template;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use uuid::Uuid; use uuid::Uuid;
@@ -27,8 +25,4 @@ impl PostEntry {
Err(e) => anyhow::bail!(e), Err(e) => anyhow::bail!(e),
} }
} }
pub fn render(&self) -> String {
PostCardTemplate { post: self }.render().unwrap()
}
} }

View File

@@ -2,31 +2,42 @@ use crate::{
domain::PostEntry, domain::PostEntry,
routes::AppError, routes::AppError,
startup::AppState, startup::AppState,
templates::{PostTemplate, PostsTemplate}, templates::{PostListTemplate, PostTemplate, PostsTemplate},
}; };
use anyhow::Context; use anyhow::Context;
use askama::Template; use askama::Template;
use axum::{ use axum::{
extract::{Path, State}, extract::{Path, Query, State},
response::{Html, IntoResponse, Response}, response::{Html, IntoResponse, Response},
}; };
use sqlx::PgPool; use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
const NUM_PER_PAGE: i64 = 3;
pub async fn list_posts( pub async fn list_posts(
State(AppState { State(AppState {
connection_pool, .. connection_pool, ..
}): State<AppState>, }): State<AppState>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
let posts = get_latest_posts(&connection_pool, 5) let count = get_posts_table_size(&connection_pool)
.await
.context("Could not fetch posts table size.")
.map_err(AppError::unexpected_page)?;
let next_page = if count > NUM_PER_PAGE { Some(2) } else { None };
let posts = get_posts(&connection_pool, NUM_PER_PAGE, None)
.await .await
.context("Could not fetch latest posts") .context("Could not fetch latest posts")
.map_err(AppError::unexpected_page)?; .map_err(AppError::unexpected_page)?;
let template = PostsTemplate { posts }; let template = PostsTemplate { posts, next_page };
Ok(Html(template.render().unwrap()).into_response()) Ok(Html(template.render().unwrap()).into_response())
} }
async fn get_latest_posts(connection_pool: &PgPool, n: i64) -> Result<Vec<PostEntry>, sqlx::Error> { async fn get_posts(
connection_pool: &PgPool,
n: i64,
offset: Option<i64>,
) -> Result<Vec<PostEntry>, sqlx::Error> {
sqlx::query_as!( sqlx::query_as!(
PostEntry, PostEntry,
r#" r#"
@@ -35,20 +46,29 @@ async fn get_latest_posts(connection_pool: &PgPool, n: i64) -> Result<Vec<PostEn
LEFT JOIN users u ON p.author_id = u.user_id LEFT JOIN users u ON p.author_id = u.user_id
ORDER BY p.published_at DESC ORDER BY p.published_at DESC
LIMIT $1 LIMIT $1
OFFSET $2
"#, "#,
n n,
offset
) )
.fetch_all(connection_pool) .fetch_all(connection_pool)
.await .await
} }
async fn get_posts_table_size(connection_pool: &PgPool) -> Result<i64, sqlx::Error> {
sqlx::query!("SELECT count(*) FROM posts")
.fetch_one(connection_pool)
.await
.map(|r| r.count.unwrap())
}
pub async fn see_post( pub async fn see_post(
State(AppState { State(AppState {
connection_pool, .. connection_pool, ..
}): State<AppState>, }): State<AppState>,
Path(post_id): Path<Uuid>, Path(post_id): Path<Uuid>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
let post = get_post(&connection_pool, post_id) let post = get_post_data(&connection_pool, post_id)
.await .await
.context(format!("Failed to fetch post #{}", post_id)) .context(format!("Failed to fetch post #{}", post_id))
.map_err(AppError::unexpected_page)? .map_err(AppError::unexpected_page)?
@@ -58,7 +78,7 @@ pub async fn see_post(
Ok(Html(template.render().unwrap()).into_response()) Ok(Html(template.render().unwrap()).into_response())
} }
async fn get_post(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry, sqlx::Error> { async fn get_post_data(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry, sqlx::Error> {
sqlx::query_as!( sqlx::query_as!(
PostEntry, PostEntry,
r#" r#"
@@ -72,3 +92,34 @@ async fn get_post(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry,
.fetch_one(connection_pool) .fetch_one(connection_pool)
.await .await
} }
#[derive(serde::Deserialize)]
pub struct LoadMoreParams {
page: i64,
}
pub async fn load_more(
State(AppState {
connection_pool, ..
}): State<AppState>,
Query(LoadMoreParams { page }): Query<LoadMoreParams>,
) -> Result<Response, AppError> {
let offset = (page - 1) * NUM_PER_PAGE;
let posts = get_posts(&connection_pool, NUM_PER_PAGE, Some(offset))
.await
.context("Could not fetch posts from database.")?;
let count = posts.len();
Ok(Html(
PostListTemplate {
posts,
next_page: if count as i64 == NUM_PER_PAGE {
Some(page + 1)
} else {
None
},
}
.render()
.unwrap(),
)
.into_response())
}

View File

@@ -135,6 +135,7 @@ pub fn app(
.route("/unsubscribe", get(get_unsubscribe).post(post_unsubscribe)) .route("/unsubscribe", get(get_unsubscribe).post(post_unsubscribe))
.route("/unsubscribe/confirm", get(unsubscribe_confirm)) .route("/unsubscribe/confirm", get(unsubscribe_confirm))
.route("/posts", get(list_posts)) .route("/posts", get(list_posts))
.route("/posts/load_more", get(load_more))
.route("/posts/{post_id}", get(see_post)) .route("/posts/{post_id}", get(see_post))
.route("/favicon.ico", get(favicon)) .route("/favicon.ico", get(favicon))
.nest("/admin", admin_routes) .nest("/admin", admin_routes)

View File

@@ -27,39 +27,47 @@ pub struct DashboardTemplate {
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/home.html")] #[template(path = "home.html")]
pub struct HomeTemplate; pub struct HomeTemplate;
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/posts.html")] #[template(path = "posts.html")]
pub struct PostsTemplate { pub struct PostsTemplate {
pub posts: Vec<PostEntry>, pub posts: Vec<PostEntry>,
pub next_page: Option<i64>,
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/post.html")] #[template(path = "posts.html", block = "posts")]
pub struct PostListTemplate {
pub posts: Vec<PostEntry>,
pub next_page: Option<i64>,
}
#[derive(Template)]
#[template(path = "post.html")]
pub struct PostTemplate { pub struct PostTemplate {
pub post: PostEntry, pub post: PostEntry,
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/confirm.html")] #[template(path = "confirm.html")]
pub struct ConfirmTemplate; pub struct ConfirmTemplate;
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/404.html")] #[template(path = "404.html")]
pub struct NotFoundTemplate; pub struct NotFoundTemplate;
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/unsubscribe_confirm.html")] #[template(path = "unsubscribe_confirm.html")]
pub struct UnsubscribeConfirmTemplate; pub struct UnsubscribeConfirmTemplate;
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/unsubscribe.html")] #[template(path = "unsubscribe.html")]
pub struct UnsubscribeTemplate; pub struct UnsubscribeTemplate;
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/email/new_post.html")] #[template(path = "email/new_post.html")]
pub struct NewPostEmailTemplate<'a> { pub struct NewPostEmailTemplate<'a> {
pub base_url: &'a str, pub base_url: &'a str,
pub post_title: &'a str, pub post_title: &'a str,
@@ -68,7 +76,7 @@ pub struct NewPostEmailTemplate<'a> {
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "../templates/email/standalone.html")] #[template(path = "email/standalone.html")]
pub struct StandaloneEmailTemplate<'a> { pub struct StandaloneEmailTemplate<'a> {
pub base_url: &'a str, pub base_url: &'a str,
pub html_content: &'a str, pub html_content: &'a str,
@@ -135,9 +143,3 @@ You're receiving this because you subscribed to the zero2prod newsletter."#,
) )
} }
} }
#[derive(Template)]
#[template(path = "../templates/post_card_fragment.html")]
pub struct PostCardTemplate<'a> {
pub post: &'a PostEntry,
}

View File

@@ -21,12 +21,23 @@
</div> </div>
{% else %} {% else %}
<div class="space-y-6"> <div class="space-y-6">
{% for post in posts %}{{ post.render() | safe }}{% endfor %} {% block posts %}
</div> {% for post in posts %}
<div class="mt-8 text-center"> {% include "post_card_fragment.html" %}
<button class="bg-blue-600 text-white hover:bg-blue-700 font-medium py-3 px-6 rounded-md transition-colors"> {% endfor %}
<div id="load-more" class="text-center">
{% if let Some(n) = next_page %}
<button hx-get="/posts/load_more?page={{ n }}"
hx-target="#load-more"
hx-swap="outerHTML"
class="text-center bg-blue-600 text-white hover:bg-blue-700 font-medium py-3 px-6 rounded-md transition-colors">
Load more Load more
</button> </button>
{% else %}
<p class="text-gray-600">No more posts. Check back later for more!</p>
{% endif %}
</div>
{% endblock %}
</div> </div>
{% endif %} {% endif %}
</div> </div>

View File

@@ -39,7 +39,7 @@
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg> </svg>
<div class="text-sm text-amber-800"> <div class="text-sm text-amber-800">
<p>You will receive an email with an unsubscribe link.</p> <p>You will receive an email with an confirmation link.</p>
</div> </div>
</div> </div>
</div> </div>