1. 请求参数:队伍 id
package com.example.usercenter.model.request;
import lombok.Data;
import java.io.Serializable;
/**
* 退出队伍请求参数封装类
*/
@Data
public class TeamQuitRequest implements Serializable {
private static final long serialVersionUID = 4442151141560122843L;
/**
* 队伍 id
*/
private Long teamId;
}
2. 请求路径:/team/quit
3. 请求方式:POST / DELETE
4. 响应数据:boolean
1. 校验请求参数
2. 校验队伍是否存在
3. 校验该用户是否已加入队伍
3. 队伍人数
@Override
@Transactional(rollbackFor = Exception.class)
public boolean quitTeam(TeamQuitRequest teamQuitRequest, User loginUser) {
// 1. 校验请求参数
if (teamQuitRequest == null) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
// 2. 校验队伍是否存在
Long teamId = teamQuitRequest.getTeamId();
Team team = this.getById(teamId);
if (team == null) {
throw new BusinessException(ErrorCode.NULL_ERROR,"队伍不存在");
}
// 3. 校验该用户是否已加入队伍
Long userId = loginUser.getId();
QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("team_id", teamId);
queryWrapper.eq("user_id", userId);
long count = userTeamService.count(queryWrapper);
if (count == 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户未加入该队伍");
}
// 4. 队伍人数
QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
userTeamQueryWrapper.eq("team_id", teamId);
long hasJoinUserNum = userTeamService.count(userTeamQueryWrapper);
if (hasJoinUserNum == 1) {
// 4.1 只剩一人,队伍解散
this.removeById(teamId);
} else {
// 4.2 还有其他人
if (Objects.equals(team.getUserId(), userId)) {
// 4.2.1 队长退出:将队长权限转移给最早加入队伍的用户(id 最小的两条数据)
userTeamQueryWrapper = new QueryWrapper<>();
userTeamQueryWrapper.eq("team_id",teamId);
userTeamQueryWrapper.last("order by id asc limit 2");
List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
if (CollectionUtils.isEmpty(userTeamList) || userTeamList.size() < 2) {
throw new BusinessException(ErrorCode.SYSTEM_ERROR);
}
// 转给最早加入的
Team updateTeam = new Team();
updateTeam.setId(teamId);
updateTeam.setUserId(userTeamList.get(1).getUserId());
boolean result = this.updateById(updateTeam);
if (!result) {
throw new BusinessException(ErrorCode.SYSTEM_ERROR, "队伍队长更新失败");
}
}
// 4.2.2 普通队员退出:直接退出
}
// 移除关系
return userTeamService.remove(queryWrapper);
}
1. 使用 Knifej 接口文档进行测试
2. 查看数据库数据变化,是否删除成功
?