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

View File

@@ -2,31 +2,42 @@ use crate::{
domain::PostEntry,
routes::AppError,
startup::AppState,
templates::{PostTemplate, PostsTemplate},
templates::{PostListTemplate, PostTemplate, PostsTemplate},
};
use anyhow::Context;
use askama::Template;
use axum::{
extract::{Path, State},
extract::{Path, Query, State},
response::{Html, IntoResponse, Response},
};
use sqlx::PgPool;
use uuid::Uuid;
const NUM_PER_PAGE: i64 = 3;
pub async fn list_posts(
State(AppState {
connection_pool, ..
}): State<AppState>,
) -> 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
.context("Could not fetch latest posts")
.map_err(AppError::unexpected_page)?;
let template = PostsTemplate { posts };
let template = PostsTemplate { posts, next_page };
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!(
PostEntry,
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
ORDER BY p.published_at DESC
LIMIT $1
OFFSET $2
"#,
n
n,
offset
)
.fetch_all(connection_pool)
.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(
State(AppState {
connection_pool, ..
}): State<AppState>,
Path(post_id): Path<Uuid>,
) -> Result<Response, AppError> {
let post = get_post(&connection_pool, post_id)
let post = get_post_data(&connection_pool, post_id)
.await
.context(format!("Failed to fetch post #{}", post_id))
.map_err(AppError::unexpected_page)?
@@ -58,7 +78,7 @@ pub async fn see_post(
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!(
PostEntry,
r#"
@@ -72,3 +92,34 @@ async fn get_post(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry,
.fetch_one(connection_pool)
.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())
}