feat: 完善后端架构 - 标准化Controller层和Service层
✨ 新功能: - 创建了完整的Service层架构,包含所有业务实体的Service接口和实现类 - 新增8个标准化的Controller类,支持完整的CRUD操作 - 实现了统一的Request/Response模式和分页查询功能 - 创建了认证服务(AuthService)和令牌服务(TokenService) - 添加了Redis配置和认证拦截器 🏗️ 架构优化: - 移除Controller层所有try-catch块,使用全局异常处理机制 - 创建了专门的异常类(AuthException, TokenException, CaptchaException) - 统一了API返回格式,完善了Result类的方法 - 实现了标准的分页查询和参数校验 📦 新增文件: - 8个Controller类: Achievement, Comment, CommunityPost, Conversation, CozeApiCall, EmotionAnalysis, Reward, UserStats - 12个Service接口和对应的实现类 - 标准化的DTO类(Request/Response) - 异常处理类和拦截器 - 测试用例 🔧 重构优化: - 重写了AuthController,移除所有业务逻辑到Service层 - 优化了MessageController,使用标准的Request/Response格式 - 更新了全局异常处理器,支持多种异常类型 - 完善了WebConfig配置,添加认证拦截器 📊 代码统计: - 新增文件: 60+个 - 新增代码行数: 8000+行 - 重构代码行数: 1000+行 - 移除过时接口: 4个
This commit is contained in:
@@ -1,18 +1,25 @@
|
||||
package com.emotion.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.emotion.common.BasePageRequest;
|
||||
import com.emotion.common.PageResult;
|
||||
import com.emotion.common.Result;
|
||||
import com.emotion.dto.request.UserCreateRequest;
|
||||
import com.emotion.dto.response.UserResponse;
|
||||
import com.emotion.entity.User;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import com.emotion.service.UserService;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用户控制器
|
||||
*
|
||||
*
|
||||
* @author emotion-museum
|
||||
* @date 2025-07-22
|
||||
*/
|
||||
@@ -20,100 +27,121 @@ import java.util.Map;
|
||||
@RequestMapping("/user")
|
||||
public class UserController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(UserController.class);
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
* 分页查询用户
|
||||
*/
|
||||
@GetMapping("/info/{userId}")
|
||||
public Result<Map<String, Object>> getUserInfo(@PathVariable String userId) {
|
||||
log.info("获取用户信息: {}", userId);
|
||||
|
||||
try {
|
||||
// 模拟用户信息
|
||||
Map<String, Object> userInfo = new HashMap<>();
|
||||
userInfo.put("id", userId);
|
||||
userInfo.put("username", "user" + userId);
|
||||
userInfo.put("account", "user" + userId);
|
||||
userInfo.put("nickname", "用户" + userId);
|
||||
userInfo.put("avatar", "https://example.com/avatar/" + userId + ".jpg");
|
||||
userInfo.put("status", 1);
|
||||
userInfo.put("memberLevel", "free");
|
||||
userInfo.put("totalDays", 30);
|
||||
userInfo.put("createTime", LocalDateTime.now().minusDays(30));
|
||||
userInfo.put("lastActiveTime", LocalDateTime.now());
|
||||
|
||||
return Result.success(userInfo);
|
||||
} catch (Exception e) {
|
||||
log.error("获取用户信息失败: {}", e.getMessage());
|
||||
return Result.error("获取用户信息失败");
|
||||
}
|
||||
@GetMapping("/page")
|
||||
public Result<PageResult<UserResponse>> getPage(@Validated BasePageRequest request) {
|
||||
IPage<User> page = userService.getPage(request);
|
||||
List<UserResponse> userResponses = page.getRecords().stream()
|
||||
.map(this::convertToResponse)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
PageResult<UserResponse> pageResult = new PageResult<>();
|
||||
pageResult.setCurrent(page.getCurrent());
|
||||
pageResult.setSize(page.getSize());
|
||||
pageResult.setTotal(page.getTotal());
|
||||
pageResult.setPages(page.getPages());
|
||||
pageResult.setRecords(userResponses);
|
||||
|
||||
return Result.success(pageResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户信息
|
||||
* 根据ID获取用户信息
|
||||
*/
|
||||
@PutMapping("/info/{userId}")
|
||||
public Result<Map<String, Object>> updateUserInfo(@PathVariable String userId,
|
||||
@RequestBody Map<String, Object> request) {
|
||||
log.info("更新用户信息: {}", userId);
|
||||
|
||||
try {
|
||||
// 模拟更新用户信息
|
||||
Map<String, Object> userInfo = new HashMap<>();
|
||||
userInfo.put("id", userId);
|
||||
userInfo.put("nickname", request.get("nickname"));
|
||||
userInfo.put("avatar", request.get("avatar"));
|
||||
userInfo.put("bio", request.get("bio"));
|
||||
userInfo.put("gender", request.get("gender"));
|
||||
userInfo.put("updateTime", LocalDateTime.now());
|
||||
|
||||
return Result.success("更新成功", userInfo);
|
||||
} catch (Exception e) {
|
||||
log.error("更新用户信息失败: {}", e.getMessage());
|
||||
return Result.error("更新用户信息失败");
|
||||
@GetMapping("/{id}")
|
||||
public Result<UserResponse> getById(@PathVariable String id) {
|
||||
User user = userService.getById(id);
|
||||
if (user == null) {
|
||||
return Result.notFound("用户不存在");
|
||||
}
|
||||
return Result.success(convertToResponse(user));
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新最后活跃时间
|
||||
* 创建用户
|
||||
*/
|
||||
@PostMapping("/active/{userId}")
|
||||
public Result<String> updateLastActiveTime(@PathVariable String userId) {
|
||||
log.info("更新最后活跃时间: {}", userId);
|
||||
|
||||
try {
|
||||
// 模拟更新活跃时间
|
||||
return Result.success("更新成功");
|
||||
} catch (Exception e) {
|
||||
log.error("更新最后活跃时间失败: {}", e.getMessage());
|
||||
@PostMapping
|
||||
public Result<UserResponse> create(@Validated @RequestBody UserCreateRequest request) {
|
||||
User user = userService.createUser(
|
||||
request.getAccount(),
|
||||
request.getUsername(),
|
||||
request.getPassword(),
|
||||
request.getEmail(),
|
||||
request.getPhone()
|
||||
);
|
||||
return Result.success(convertToResponse(user));
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户
|
||||
*/
|
||||
@PutMapping("/{id}")
|
||||
public Result<UserResponse> update(@PathVariable String id, @RequestBody User user) {
|
||||
user.setId(id);
|
||||
boolean updated = userService.updateById(user);
|
||||
if (!updated) {
|
||||
return Result.error("更新失败");
|
||||
}
|
||||
User updatedUser = userService.getById(id);
|
||||
return Result.success(convertToResponse(updatedUser));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户统计信息
|
||||
* 删除用户
|
||||
*/
|
||||
@GetMapping("/stats/{userId}")
|
||||
public Result<Map<String, Object>> getUserStats(@PathVariable String userId) {
|
||||
log.info("获取用户统计信息: {}", userId);
|
||||
|
||||
try {
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
stats.put("totalDays", 30);
|
||||
stats.put("totalRecords", 45);
|
||||
stats.put("totalConversations", 12);
|
||||
stats.put("totalMessages", 156);
|
||||
stats.put("selfAwareness", 75.5);
|
||||
stats.put("emotionalResilience", 68.2);
|
||||
stats.put("actionPower", 82.1);
|
||||
stats.put("empathy", 79.3);
|
||||
stats.put("lifeEnthusiasm", 85.7);
|
||||
|
||||
return Result.success(stats);
|
||||
} catch (Exception e) {
|
||||
log.error("获取用户统计信息失败: {}", e.getMessage());
|
||||
return Result.error("获取统计信息失败");
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> delete(@PathVariable String id) {
|
||||
boolean deleted = userService.removeById(id);
|
||||
if (!deleted) {
|
||||
return Result.error("删除失败");
|
||||
}
|
||||
return Result.success();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据账号查询用户
|
||||
*/
|
||||
@GetMapping("/account/{account}")
|
||||
public Result<UserResponse> getByAccount(@PathVariable String account) {
|
||||
User user = userService.getByAccount(account);
|
||||
if (user == null) {
|
||||
return Result.notFound("用户不存在");
|
||||
}
|
||||
return Result.success(convertToResponse(user));
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计用户数量
|
||||
*/
|
||||
@GetMapping("/count/status/{status}")
|
||||
public Result<Long> countByStatus(@PathVariable Integer status) {
|
||||
Long count = userService.countByStatus(status);
|
||||
return Result.success(count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为响应对象
|
||||
*/
|
||||
private UserResponse convertToResponse(User user) {
|
||||
UserResponse response = new UserResponse();
|
||||
BeanUtils.copyProperties(user, response);
|
||||
response.setId(user.getId());
|
||||
if (user.getCreateTime() != null) {
|
||||
response.setCreateTime(user.getCreateTime().format(DATE_TIME_FORMATTER));
|
||||
}
|
||||
if (user.getUpdateTime() != null) {
|
||||
response.setUpdateTime(user.getUpdateTime().format(DATE_TIME_FORMATTER));
|
||||
}
|
||||
if (user.getLastActiveTime() != null) {
|
||||
response.setLastActiveTime(user.getLastActiveTime().format(DATE_TIME_FORMATTER));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user