added get_one, get_popular datasource methods, added respective routes

This commit is contained in:
2024-09-26 13:11:55 -04:00
parent 9bd2cf373a
commit e3e81f6685
6 changed files with 125 additions and 32 deletions

View File

@@ -1,3 +1,4 @@
use axum::routing::trace;
use sqlx::{PgPool, Pool, Postgres};
use crate::routes::posts::Post;
@@ -5,11 +6,20 @@ use crate::routes::posts::Post;
pub struct PostsDatasource;
impl PostsDatasource {
pub async fn get_all(pool: &Pool<Postgres>) -> Result<Vec<Post>, sqlx::Error> {
sqlx::query_as::<_, Post>(
"SELECT post_id, title, body, created_at FROM posts ORDER BY created_at DESC LIMIT 10",
)
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.created_at DESC LIMIT 10")
.fetch_all(pool)
.await
}
pub async fn get_one(pool: &Pool<Postgres>, post_id: i32) -> Result<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 AND p.post_id = $1 ORDER BY p.created_at DESC", post_id)
.fetch_one(pool)
.await
}
pub async fn get_popular(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 LEFT JOIN comments c ON p.post_id = c.post_id WHERE p.deleted_at IS NULL GROUP BY p.post_id, a.first_name, a.last_name ORDER BY p.created_at DESC LIMIT 3")
.fetch_all(pool)
.await
}
pub async fn get_one(pool: PgPool, post_id: i32) {}
}