Load more button on Posts page
This commit is contained in:
@@ -1,5 +1,3 @@
|
||||
use crate::templates::PostCardTemplate;
|
||||
use askama::Template;
|
||||
use chrono::{DateTime, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -27,8 +25,4 @@ impl PostEntry {
|
||||
Err(e) => anyhow::bail!(e),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
PostCardTemplate { post: self }.render().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ pub fn app(
|
||||
.route("/unsubscribe", get(get_unsubscribe).post(post_unsubscribe))
|
||||
.route("/unsubscribe/confirm", get(unsubscribe_confirm))
|
||||
.route("/posts", get(list_posts))
|
||||
.route("/posts/load_more", get(load_more))
|
||||
.route("/posts/{post_id}", get(see_post))
|
||||
.route("/favicon.ico", get(favicon))
|
||||
.nest("/admin", admin_routes)
|
||||
|
||||
@@ -27,39 +27,47 @@ pub struct DashboardTemplate {
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/home.html")]
|
||||
#[template(path = "home.html")]
|
||||
pub struct HomeTemplate;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/posts.html")]
|
||||
#[template(path = "posts.html")]
|
||||
pub struct PostsTemplate {
|
||||
pub posts: Vec<PostEntry>,
|
||||
pub next_page: Option<i64>,
|
||||
}
|
||||
|
||||
#[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 post: PostEntry,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/confirm.html")]
|
||||
#[template(path = "confirm.html")]
|
||||
pub struct ConfirmTemplate;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/404.html")]
|
||||
#[template(path = "404.html")]
|
||||
pub struct NotFoundTemplate;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/unsubscribe_confirm.html")]
|
||||
#[template(path = "unsubscribe_confirm.html")]
|
||||
pub struct UnsubscribeConfirmTemplate;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/unsubscribe.html")]
|
||||
#[template(path = "unsubscribe.html")]
|
||||
pub struct UnsubscribeTemplate;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/email/new_post.html")]
|
||||
#[template(path = "email/new_post.html")]
|
||||
pub struct NewPostEmailTemplate<'a> {
|
||||
pub base_url: &'a str,
|
||||
pub post_title: &'a str,
|
||||
@@ -68,7 +76,7 @@ pub struct NewPostEmailTemplate<'a> {
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "../templates/email/standalone.html")]
|
||||
#[template(path = "email/standalone.html")]
|
||||
pub struct StandaloneEmailTemplate<'a> {
|
||||
pub base_url: &'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,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user