From 4480b87cabce977695fea475f206e9aad3ca3d96 Mon Sep 17 00:00:00 2001 From: "Wyatt J. Miller" Date: Sat, 28 Sep 2024 02:26:17 -0400 Subject: [PATCH] added get authors posts route, datasource --- backend/public/src/datasources/authors.rs | 15 ++++++++++++++- backend/public/src/routes/authors.rs | 11 +++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/backend/public/src/datasources/authors.rs b/backend/public/src/datasources/authors.rs index fb1f17b..15eb4e6 100644 --- a/backend/public/src/datasources/authors.rs +++ b/backend/public/src/datasources/authors.rs @@ -1,6 +1,6 @@ use sqlx::{Pool, Postgres}; -use crate::routes::{authors::Author, comments::Pagination}; +use crate::routes::{authors::Author, comments::Pagination, posts::Post}; pub struct AuthorsDatasource; impl AuthorsDatasource { @@ -28,4 +28,17 @@ impl AuthorsDatasource { .fetch_one(pool) .await } + + pub async fn get_authors_posts( + pool: &Pool, + author_id: i32, + ) -> 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 AND p.author_id = $1 ORDER BY created_at DESC", + author_id + ) + .fetch_all(pool) + .await + } } diff --git a/backend/public/src/routes/authors.rs b/backend/public/src/routes/authors.rs index 903dabe..33e26fc 100644 --- a/backend/public/src/routes/authors.rs +++ b/backend/public/src/routes/authors.rs @@ -31,6 +31,7 @@ impl AuthorsRoute { axum::Router::new() .route("/", get(AuthorsRoute::get_all)) .route("/:id", get(AuthorsRoute::get_one)) + .route("/:id/posts", get(AuthorsRoute::get_authors_posts)) .with_state(app_state.db.clone()) } @@ -53,4 +54,14 @@ impl AuthorsRoute { Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), } } + + async fn get_authors_posts( + State(pool): State>, + Path(params): Path, + ) -> impl IntoResponse { + match AuthorsDatasource::get_authors_posts(&pool, params.id).await { + Ok(p) => Ok(Json(p)), + Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), + } + } }