From c303e6aaeef44166e0f53020286eeb1f2a31d6b8 Mon Sep 17 00:00:00 2001 From: "Wyatt J. Miller" Date: Thu, 26 Sep 2024 23:53:39 -0400 Subject: [PATCH] added hot posts datasource, added respective route, added view_count updating --- backend/public/src/datasources/posts.rs | 14 ++++++++++++-- backend/public/src/routes/posts.rs | 8 +++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/backend/public/src/datasources/posts.rs b/backend/public/src/datasources/posts.rs index d560a43..8b2afc7 100644 --- a/backend/public/src/datasources/posts.rs +++ b/backend/public/src/datasources/posts.rs @@ -1,5 +1,4 @@ -use axum::routing::trace; -use sqlx::{PgPool, Pool, Postgres}; +use sqlx::{Pool, Postgres}; use crate::routes::posts::Post; @@ -12,6 +11,11 @@ impl PostsDatasource { } pub async fn get_one(pool: &Pool, post_id: i32) -> Result { + let _ = sqlx::query("UPDATE posts SET view_count = view_count + 1 WHERE post_id = $1") + .bind(post_id) + .execute(pool) + .await; + sqlx::query_as!(Post, "SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.created_at FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL AND p.post_id = $1 ORDER BY p.created_at DESC", post_id) .fetch_one(pool) .await @@ -22,4 +26,10 @@ impl PostsDatasource { .fetch_all(pool) .await } + + pub async fn get_hot(pool: &Pool) -> Result, sqlx::Error> { + sqlx::query_as!(Post, "SELECT p.post_id, a.first_name, a.last_name, p.title, p.body, p.created_at FROM posts p LEFT JOIN authors a ON a.author_id = p.author_id WHERE p.deleted_at IS NULL ORDER BY p.view_count DESC LIMIT 3") + .fetch_all(pool) + .await + } } diff --git a/backend/public/src/routes/posts.rs b/backend/public/src/routes/posts.rs index 488252b..5210cbd 100644 --- a/backend/public/src/routes/posts.rs +++ b/backend/public/src/routes/posts.rs @@ -34,6 +34,7 @@ impl PostsRoute { .route("/all", get(PostsRoute::get_all)) .route("/:id", get(PostsRoute::get_one)) .route("/popular", get(PostsRoute::get_popular_posts)) + .route("/hot", get(PostsRoute::get_hot_posts)) .with_state(app_state.db.clone()) } @@ -65,7 +66,12 @@ impl PostsRoute { } // get the top three posts with the highest view count - // async fn get_hot_posts(State(pool): State) {} + async fn get_hot_posts(State(pool): State>) -> impl IntoResponse { + match PostsDatasource::get_hot(&pool).await { + Ok(posts) => Ok(Json(posts)), + Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), + } + } } fn serialize_datetime(