added pagination to a given authors page

This commit is contained in:
wymiller committed 2025-07-07 21:05:27 -04:00
1 parent a64b8fdceb
commit 6694f47d70
16 files changed
+350 -93

No files matched your search

+33 -10
View File
@@ -1,5 +1,5 @@
use axum::{
extract::{Path, State},
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
routing::get,
@@ -8,9 +8,12 @@ use axum::{
use fred::types::Expiration;
use serde::{Deserialize, Serialize};
use crate::{datasources::authors::AuthorsDatasource, state::AppState};
use super::comments::Pagination;
use crate::{
datasources::authors::AuthorsDatasource,
routes::posts::Post,
state::AppState,
utils::pagination::{Pagination, PaginationQuery},
};
#[derive(Deserialize, Serialize, Clone)]
pub struct Author {
@@ -26,20 +29,31 @@ pub struct AuthorGetOneParams {
pub id: i32,
}
#[derive(Deserialize, Serialize)]
pub struct AuthorPostsResponse {
posts: Vec<Post>,
total_posts: i64,
}
pub struct AuthorsRoute;
impl AuthorsRoute {
pub fn routes(app_state: &AppState) -> axum::Router {
axum::Router::new()
.route("/", get(AuthorsRoute::get_all))
.route("/:id", get(AuthorsRoute::get_one))
.route("/:id/posts", get(AuthorsRoute::get_authors_posts))
.route("/authors", get(AuthorsRoute::get_all))
.route("/authors/{id}", get(AuthorsRoute::get_one))
.route("/authors/{id}/posts", get(AuthorsRoute::get_authors_posts))
.with_state(app_state.clone())
}
async fn get_all(
State(app_state): State<AppState>,
Json(pagination): Json<Pagination>,
Query(query): Query<PaginationQuery>,
) -> impl IntoResponse {
let pagination = Pagination {
page: query.page.unwrap_or(1),
limit: query.limit.unwrap_or(12),
};
let mut state = app_state.lock().await;
let cached: Option<Vec<Author>> = state
.cache
@@ -104,6 +118,7 @@ impl AuthorsRoute {
let state = app_state.clone();
tracing::info!("storing database data in cache");
tokio::spawn(async move {
let mut s = state.lock().await;
let _ = s
@@ -127,12 +142,20 @@ impl AuthorsRoute {
async fn get_authors_posts(
State(app_state): State<AppState>,
Path(params): Path<AuthorGetOneParams>,
Query(pagination): Query<PaginationQuery>,
) -> impl IntoResponse {
let pagination = Pagination {
page: pagination.page.unwrap_or(1),
limit: pagination.limit.unwrap_or(12),
};
let state = app_state.lock().await;
match AuthorsDatasource::get_authors_posts(&state.database, params.id).await {
Ok(p) => Ok(Json(p)),
match AuthorsDatasource::get_authors_posts(&state.database, params.id, pagination).await {
Ok((posts, total_posts)) => Ok(Json(AuthorPostsResponse { posts, total_posts })),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
}