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

This commit is contained in:
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
}
}