feat: GET /users (search/list) and GET /users/count

This commit is contained in:
2026-05-14 15:34:37 +02:00
parent a2cc4fba21
commit eb7dbb0aee
4 changed files with 62 additions and 1 deletions

View File

@@ -176,6 +176,13 @@ impl UserRepository for PgUserRepository {
following_count: r.following_count, following_count: r.following_count,
}).collect()) }).collect())
} }
async fn count(&self) -> Result<i64, DomainError> {
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM users WHERE local = true")
.fetch_one(&self.pool)
.await
.map_err(|e| DomainError::Internal(e.to_string()))
}
} }
#[cfg(test)] #[cfg(test)]

View File

@@ -47,6 +47,7 @@ pub trait UserRepository: Send + Sync {
async fn save(&self, user: &User) -> Result<(), DomainError>; async fn save(&self, user: &User) -> Result<(), DomainError>;
async fn update_profile(&self, user_id: &UserId, display_name: Option<String>, bio: Option<String>, avatar_url: Option<String>, header_url: Option<String>, custom_css: Option<String>) -> Result<(), DomainError>; async fn update_profile(&self, user_id: &UserId, display_name: Option<String>, bio: Option<String>, avatar_url: Option<String>, header_url: Option<String>, custom_css: Option<String>) -> Result<(), DomainError>;
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>; async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>;
async fn count(&self) -> Result<i64, DomainError>;
} }
#[async_trait] #[async_trait]
@@ -100,6 +101,8 @@ pub trait TagRepository: Send + Sync {
async fn detach_from_thought(&self, thought_id: &ThoughtId) -> Result<(), DomainError>; async fn detach_from_thought(&self, thought_id: &ThoughtId) -> Result<(), DomainError>;
async fn list_for_thought(&self, thought_id: &ThoughtId) -> Result<Vec<Tag>, DomainError>; async fn list_for_thought(&self, thought_id: &ThoughtId) -> Result<Vec<Tag>, DomainError>;
async fn list_thoughts_by_tag(&self, tag_name: &str, page: &PageParams) -> Result<Paginated<Thought>, DomainError>; async fn list_thoughts_by_tag(&self, tag_name: &str, page: &PageParams) -> Result<Paginated<Thought>, DomainError>;
/// Returns (tag_name, thought_count) pairs ordered by usage, most popular first.
async fn popular_tags(&self, limit: usize) -> Result<Vec<(String, i64)>, DomainError>;
} }
#[async_trait] #[async_trait]

View File

@@ -62,6 +62,9 @@ pub struct TestStore {
Ok(()) Ok(())
} }
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError> { Ok(vec![]) } async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError> { Ok(vec![]) }
async fn count(&self) -> Result<i64, DomainError> {
Ok(self.users.lock().unwrap().iter().filter(|u| u.local).count() as i64)
}
} }
#[async_trait] impl ThoughtRepository for TestStore { #[async_trait] impl ThoughtRepository for TestStore {
@@ -211,6 +214,9 @@ pub struct TestStore {
async fn list_thoughts_by_tag(&self, _name: &str, _p: &PageParams) -> Result<Paginated<Thought>, DomainError> { async fn list_thoughts_by_tag(&self, _name: &str, _p: &PageParams) -> Result<Paginated<Thought>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 }) Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
} }
async fn popular_tags(&self, _limit: usize) -> Result<Vec<(String, i64)>, DomainError> {
Ok(vec![])
}
} }
#[async_trait] impl ApiKeyRepository for TestStore { #[async_trait] impl ApiKeyRepository for TestStore {

View File

@@ -1,4 +1,4 @@
use axum::{extract::{Path, State}, Json}; use axum::{extract::{Path, Query, State}, Json};
use api_types::{requests::UpdateProfileRequest, responses::{ErrorResponse, UserResponse}}; use api_types::{requests::UpdateProfileRequest, responses::{ErrorResponse, UserResponse}};
use application::use_cases::profile::{get_user_by_username, update_profile}; use application::use_cases::profile::{get_user_by_username, update_profile};
use crate::{errors::ApiError, extractors::AuthUser, handlers::auth::to_user_response, state::AppState}; use crate::{errors::ApiError, extractors::AuthUser, handlers::auth::to_user_response, state::AppState};
@@ -43,3 +43,48 @@ pub async fn get_me(State(s): State<AppState>, AuthUser(uid): AuthUser) -> Resul
let user = s.users.find_by_id(&uid).await?.ok_or(domain::errors::DomainError::NotFound)?; let user = s.users.find_by_id(&uid).await?.ok_or(domain::errors::DomainError::NotFound)?;
Ok(Json(to_user_response(&user))) Ok(Json(to_user_response(&user)))
} }
pub async fn get_users(
State(s): State<AppState>,
Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>, ApiError> {
use domain::models::feed::PageParams;
let page = params.get("page").and_then(|v| v.parse::<u64>().ok()).unwrap_or(1);
let per_page = params.get("per_page").and_then(|v| v.parse::<u64>().ok()).unwrap_or(20);
let page_params = PageParams { page, per_page };
if let Some(q) = params.get("q").filter(|q| !q.trim().is_empty()) {
let result = s.search.search_users(q, &page_params).await?;
let users: Vec<_> = result.items.iter().map(|u| crate::handlers::auth::to_user_response(u)).collect();
return Ok(Json(serde_json::json!({
"items": users, "total": result.total, "page": result.page, "per_page": result.per_page
})));
}
let all = s.users.list_with_stats().await?;
let total = all.len() as i64;
let start = ((page - 1) * per_page) as usize;
let items: Vec<_> = all.into_iter()
.skip(start).take(per_page as usize)
.map(|u| serde_json::json!({
"id": u.id.as_uuid(),
"username": u.username,
"display_name": u.display_name,
"avatar_url": u.avatar_url,
"bio": u.bio,
"thought_count": u.thought_count,
"follower_count": u.follower_count,
"following_count": u.following_count,
}))
.collect();
Ok(Json(serde_json::json!({
"items": items, "total": total, "page": page, "per_page": per_page
})))
}
pub async fn get_user_count(
State(s): State<AppState>,
) -> Result<Json<serde_json::Value>, ApiError> {
let count = s.users.count().await?;
Ok(Json(serde_json::json!({ "count": count })))
}