api/routes/test/
delete.rs

1use axum::{
2    extract::{Path, State},
3    http::StatusCode,
4    response::IntoResponse,
5    Json,
6};
7use sea_orm::{ActiveModelTrait, EntityTrait};
8use util::state::AppState;
9
10use crate::response::ApiResponse;
11use db::models::user::{ActiveModel as UserActiveModel, Entity as UserEntity};
12
13/// DELETE `/api/test/users/{user_id}`
14///
15/// Deletes a user by their **numeric ID**.  
16/// Intended for **test environment teardown** in non-production environments.
17///
18/// # Path parameters
19/// - `user_id` — The primary key of the user to delete.
20///
21/// # Example request
22/// ```bash
23/// curl -X DELETE http://localhost:3000/api/test/users/1
24/// ```
25///
26/// ## 200 OK
27/// ```json
28/// { "success": true, "data": null, "message": "User deleted" }
29/// ```
30///
31/// ## 404 Not Found
32/// ```json
33/// { "success": false, "data": null, "message": "User not found" }
34/// ```
35pub async fn delete_user(
36    State(app): State<AppState>,
37    Path(user_id): Path<i32>,
38) -> impl IntoResponse {
39    let db = app.db();
40
41    match UserEntity::find_by_id(user_id).one(db).await {
42        Ok(Some(user)) => {
43            let am: UserActiveModel = user.into();
44            if let Err(e) = am.delete(db).await {
45                return (
46                    StatusCode::INTERNAL_SERVER_ERROR,
47                    Json(ApiResponse::<()>::error(format!("Database error: {e}"))),
48                )
49                    .into_response();
50            }
51            (
52                StatusCode::OK,
53                Json(ApiResponse::<()>::success((), "User deleted")),
54            )
55                .into_response()
56        }
57        Ok(None) => (
58            StatusCode::NOT_FOUND,
59            Json(ApiResponse::<()>::error("User not found")),
60        )
61            .into_response(),
62        Err(e) => (
63            StatusCode::INTERNAL_SERVER_ERROR,
64            Json(ApiResponse::<()>::error(format!("Database error: {e}"))),
65        )
66            .into_response(),
67    }
68}