ruskit/app/controllers/
user_controller.rs

1// Framework imports from prelude
2use crate::framework::prelude::*;
3// App-specific imports
4use crate::app::entities::User;
5use crate::app::dtos::user::{CreateUserRequest, UserResponse, UserListResponse};
6
7/// User Controller handling all user-related endpoints
8pub struct UserController;
9
10impl UserController {
11    /// Returns a list of users
12    pub async fn index() -> impl IntoResponse {
13        match User::all().await {
14            Ok(users) => Json(UserListResponse::from(users)),
15            Err(e) => panic!("Database error: {}", e), // In a real app, use proper error handling
16        }
17    }
18
19    /// Returns details for a specific user
20    pub async fn show(Path(id): Path<i64>) -> impl IntoResponse {
21        match User::find(id).await {
22            Ok(Some(user)) => Json(Some(UserResponse::from(user))),
23            Ok(None) => Json(None::<UserResponse>),
24            Err(e) => panic!("Database error: {}", e), // In a real app, use proper error handling
25        }
26    }
27
28    /// Creates a new user
29    pub async fn store(Json(payload): Json<CreateUserRequest>) -> Json<UserResponse> {
30        let user: User = payload.into();
31        match User::create(user).await {
32            Ok(user) => Json(UserResponse::from(user)),
33            Err(e) => panic!("Database error: {}", e), // In a real app, use proper error handling
34        }
35    }
36
37    pub async fn recent() -> impl IntoResponse {
38        match User::recent(10).await {
39            Ok(users) => Json(UserListResponse::from(users)),
40            Err(e) => panic!("Database error: {}", e), // In a real app, use proper error handling
41        }
42    }
43}