diff --git a/src/api/posts/list.rs b/src/api/posts/list.rs index 87def46..c2cb1f4 100644 --- a/src/api/posts/list.rs +++ b/src/api/posts/list.rs @@ -20,15 +20,21 @@ pub async fn list_published_posts( let client = get_conn().await.map_err(AppError::db_conn)?; - // Get total count - let count_row = client - .query_one( - "SELECT COUNT(*) FROM posts WHERE status = 'published' AND deleted_at IS NULL", - &[], - ) - .await - .map_err(AppError::query)?; - let total: i64 = count_row.get(0); + // Get total count from cache or query + let total = if let Some(cached_total) = crate::cache::get_total_published_posts().await { + cached_total + } else { + let count_row = client + .query_one( + "SELECT COUNT(*) FROM posts WHERE status = 'published' AND deleted_at IS NULL", + &[], + ) + .await + .map_err(AppError::query)?; + let total: i64 = count_row.get(0); + crate::cache::set_total_published_posts(total).await; + total + }; let offset = ((page - 1).max(0) as i64) * (per_page as i64); let limit = per_page as i64; @@ -139,6 +145,9 @@ pub async fn get_posts_by_tag(tag_name: String) -> Result, total: i64) { let _ = POST_LIST_CACHE.insert(key.clone(), (posts, total)).await; } +#[cfg(feature = "server")] +pub async fn get_total_published_posts() -> Option { + POST_LIST_CACHE.get(&CacheKey::TotalPublishedPosts).await.map(|(_, total)| total) +} + +#[cfg(feature = "server")] +pub async fn set_total_published_posts(total: i64) { + let _ = POST_LIST_CACHE.insert(CacheKey::TotalPublishedPosts, (vec![], total)).await; +} + #[cfg(feature = "server")] pub async fn get_tag_list() -> Option> { TAG_LIST_CACHE.get(&CacheKey::AllTags).await