added hot posts datasource, added respective route, added view_count updating

This commit is contained in:
Wyatt J. Miller 2024-09-26 23:53:39 -04:00
parent b427311742
commit c303e6aaee
2 changed files with 19 additions and 3 deletions

View File

@ -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<Postgres>, post_id: i32) -> Result<Post, sqlx::Error> {
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<Postgres>) -> Result<Vec<Post>, 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
}
}

View File

@ -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<PgPool>) {}
async fn get_hot_posts(State(pool): State<Pool<Postgres>>) -> 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<S>(