2024-09-28 01:48:58 -04:00
|
|
|
use axum::{
|
|
|
|
extract::{Path, State},
|
|
|
|
http::StatusCode,
|
|
|
|
response::IntoResponse,
|
|
|
|
routing::get,
|
|
|
|
Json,
|
|
|
|
};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use sqlx::{Pool, Postgres};
|
|
|
|
|
|
|
|
use crate::{datasources::authors::AuthorsDatasource, AppState};
|
|
|
|
|
|
|
|
use super::comments::Pagination;
|
|
|
|
|
|
|
|
#[derive(Serialize)]
|
|
|
|
pub struct Author {
|
|
|
|
pub author_id: i32,
|
|
|
|
pub first_name: String,
|
|
|
|
pub last_name: String,
|
|
|
|
pub bio: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct AuthorGetOneParams {
|
|
|
|
pub id: i32,
|
|
|
|
}
|
|
|
|
|
2024-09-22 22:38:35 -04:00
|
|
|
pub struct AuthorsRoute;
|
2024-09-28 01:48:58 -04:00
|
|
|
impl AuthorsRoute {
|
|
|
|
pub fn routes(app_state: &AppState) -> axum::Router {
|
|
|
|
axum::Router::new()
|
|
|
|
.route("/", get(AuthorsRoute::get_all))
|
|
|
|
.route("/:id", get(AuthorsRoute::get_one))
|
2024-09-28 02:26:17 -04:00
|
|
|
.route("/:id/posts", get(AuthorsRoute::get_authors_posts))
|
2024-09-28 01:48:58 -04:00
|
|
|
.with_state(app_state.db.clone())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn get_all(
|
|
|
|
State(pool): State<Pool<Postgres>>,
|
|
|
|
Json(pagination): Json<Pagination>,
|
|
|
|
) -> impl IntoResponse {
|
|
|
|
match AuthorsDatasource::get_all(&pool, pagination).await {
|
|
|
|
Ok(a) => Ok(Json(a)),
|
|
|
|
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn get_one(
|
|
|
|
State(pool): State<Pool<Postgres>>,
|
|
|
|
Path(params): Path<AuthorGetOneParams>,
|
|
|
|
) -> impl IntoResponse {
|
|
|
|
match AuthorsDatasource::get_one(&pool, params.id).await {
|
|
|
|
Ok(a) => Ok(Json(a)),
|
|
|
|
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
|
|
|
|
}
|
|
|
|
}
|
2024-09-28 02:26:17 -04:00
|
|
|
|
|
|
|
async fn get_authors_posts(
|
|
|
|
State(pool): State<Pool<Postgres>>,
|
|
|
|
Path(params): Path<AuthorGetOneParams>,
|
|
|
|
) -> 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())),
|
|
|
|
}
|
|
|
|
}
|
2024-09-28 01:48:58 -04:00
|
|
|
}
|