use crate::repositories::user_repository::UserRepository; use crate::services::user_service; use crate::{models::user::User, services::user_service::UserServiceError}; use actix_web::{post, web, HttpResponse, Responder}; use r2d2_mysql::MySqlConnectionManager; use serde::Serialize; #[derive(Serialize)] struct ApiResponse { status: String, message: Option, error: Option, } pub(crate) fn register(config: &mut web::ServiceConfig) { config.service(register_user); } #[derive(serde::Deserialize)] struct UserFrom { account: String, name: String, password: String, } #[post("/user/register")] async fn register_user( user_from: web::Form, pool: web::Data>, ) -> impl Responder { let user_repository = UserRepository::new(pool.get_ref().clone()); let user_service = user_service::UserService::new(user_repository); let user = User { id: None, account: Some(user_from.account.clone()), name: Some(user_from.name.clone()), birth: None, email: None, password: Some(user_from.password.clone()), phone: None, status: None, created_time: None, updated_time: None, }; match user_service.insert_user(&user) { Ok(_) => HttpResponse::Ok().json(ApiResponse { status: "success".to_string(), message: Some("User created successfully".to_string()), error: None, }), Err(e) => { // 根据错误类型返回不同的 HTTP 状态码 let response = if matches!(e, UserServiceError::MissingField(_)) { HttpResponse::BadRequest().json(ApiResponse::<()> { status: "error".to_string(), message: None, error: Some(e.to_string()), }) } else { HttpResponse::InternalServerError().json(ApiResponse::<()> { status: "error".to_string(), message: None, error: Some(e.to_string()), }) }; response } } }