api/routes/test/get.rs
1use axum::{
2 extract::{Query, State},
3 http::StatusCode,
4 response::IntoResponse,
5 Json,
6};
7use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
8use serde::Deserialize;
9use util::state::AppState;
10
11use crate::response::ApiResponse;
12use db::models::user::{Column as UserColumn, Entity as UserEntity};
13
14use super::common::TestUserResponse;
15
16/// Query parameters for fetching a test user.
17#[derive(Debug, Deserialize)]
18pub struct GetUserParams {
19 /// The unique username of the user to fetch.
20 pub username: String,
21}
22
23/// GET `/api/test/users?username={username}`
24///
25/// Fetches a user by their username.
26///
27/// This endpoint is **only available in non-production environments**
28/// and exists for the sole purpose of E2E/integration tests.
29/// It must never be exposed in production.
30///
31/// # Query parameters
32///
33/// - `username` — The unique username of the user to fetch.
34///
35/// # Example request
36///
37/// ```bash
38/// curl -X GET "http://localhost:3000/api/test/users?username=student42"
39/// ```
40///
41/// # Response examples
42///
43/// ## 200 OK
44/// ```json
45/// {
46/// "success": true,
47/// "data": {
48/// "id": 1,
49/// "username": "student42",
50/// "email": "[email protected]",
51/// "admin": false
52/// },
53/// "message": "OK"
54/// }
55/// ```
56///
57/// ## 404 Not Found
58/// ```json
59/// {
60/// "success": false,
61/// "data": null,
62/// "message": "User not found"
63/// }
64/// ```
65///
66/// ## 500 Internal Server Error
67/// ```json
68/// {
69/// "success": false,
70/// "data": null,
71/// "message": "Database error: <details>"
72/// }
73/// ```
74pub async fn get_user(
75 State(app): State<AppState>,
76 Query(params): Query<GetUserParams>,
77) -> impl IntoResponse {
78 let db = app.db();
79
80 match UserEntity::find()
81 .filter(UserColumn::Username.eq(params.username.clone()))
82 .one(db)
83 .await
84 {
85 Ok(Some(user)) => (
86 StatusCode::OK,
87 Json(ApiResponse::success(
88 TestUserResponse::from(user),
89 "OK".to_string(),
90 )),
91 )
92 .into_response(),
93 Ok(None) => (
94 StatusCode::NOT_FOUND,
95 Json(ApiResponse::<()>::error("User not found".to_string())),
96 )
97 .into_response(),
98 Err(e) => (
99 StatusCode::INTERNAL_SERVER_ERROR,
100 Json(ApiResponse::<()>::error(format!("Database error: {e}"))),
101 )
102 .into_response(),
103 }
104}