Skip to content

Commit

Permalink
chore: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
bs32g1038 committed Apr 24, 2024
1 parent d2f32df commit 7744db2
Show file tree
Hide file tree
Showing 25 changed files with 236 additions and 388 deletions.
42 changes: 15 additions & 27 deletions server/src/main/java/com/jixialunbi/common/R.java
Original file line number Diff line number Diff line change
@@ -1,54 +1,47 @@
package com.jixialunbi.common;

import com.jixialunbi.enums.HttpReponseResultCodeEnum;
import com.jixialunbi.common.result.ResultCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.util.Map;
import java.io.Serializable;

/**
* - 全局统一返回结果
*/
@Data
@Schema(name = "全局统一返回结果", description = "全局统一返回结果")
public class R {
public class R<T> implements Serializable {

@Schema(description = "是否成功")
private Boolean success;

@Schema(description = "返回码")
private Integer code;
private String code;

@Schema(description = "返回消息")
private String message;

@Schema(description = "返回数据")
private Object data;
private T data;

public R() {
}

public static R ok() {
R r = new R();
r.setSuccess(HttpReponseResultCodeEnum.SUCCESS.getSuccess());
r.setCode(HttpReponseResultCodeEnum.SUCCESS.getCode());
r.setMessage(HttpReponseResultCodeEnum.SUCCESS.getMessage());
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS.getCode());
r.setMessage(ResultCode.SUCCESS.getMessage());
return r;
}

public static R error() {
public static R error(ResultCode resultCode) {
R r = new R();
r.setSuccess(HttpReponseResultCodeEnum.UNKNOWN_REASON.getSuccess());
r.setCode(HttpReponseResultCodeEnum.UNKNOWN_REASON.getCode());
r.setMessage(HttpReponseResultCodeEnum.UNKNOWN_REASON.getMessage());
return r;
}

public static R setResult(HttpReponseResultCodeEnum resultCodeEnum) {
R r = new R();
r.setSuccess(resultCodeEnum.getSuccess());
r.setCode(resultCodeEnum.getCode());
r.setMessage(resultCodeEnum.getMessage());
r.setSuccess(false);
r.setCode(resultCode.getCode());
r.setMessage(resultCode.getMessage());
r.setData(null);
return r;
}

Expand All @@ -62,19 +55,14 @@ public R message(String message) {
return this;
}

public R code(Integer code) {
public R code(String code) {
this.setCode(code);
return this;
}

public R data(Object value) {
public R data(T value) {
this.data = value;
return this;
}

public R data(Map<String, Object> map) {
this.setData(map);
return this;
}

}
12 changes: 12 additions & 0 deletions server/src/main/java/com/jixialunbi/common/result/IResultCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.jixialunbi.common.result;

/**
* @author haoxr
**/
public interface IResultCode {

String getCode();

String getMessage();

}
107 changes: 107 additions & 0 deletions server/src/main/java/com/jixialunbi/common/result/ResultCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package com.jixialunbi.common.result;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
* 前后端数据交换状态码
*
* @author haoxr
* @since 2020-06-23
**/
@AllArgsConstructor
@NoArgsConstructor
public enum ResultCode implements IResultCode, Serializable {

SUCCESS("00000", "成功"),

USER_ERROR("A0001", "用户端错误"),
REPEAT_SUBMIT_ERROR("A0002", "您的请求已提交,请不要重复提交或等待片刻再尝试。"),
USER_LOGIN_ERROR("A0200", "用户登录异常"),
USER_NOT_EXIST("A0201", "用户不存在"),
USERNAME_OR_PASSWORD_ERROR("A0210", "用户名或密码错误"),
PASSWORD_ENTER_EXCEED_LIMIT("A0211", "用户输入密码次数超限"),
CLIENT_AUTHENTICATION_FAILED("A0212", "客户端认证失败"),

VERIFY_CODE_TIMEOUT("A0213", "验证码已过期"),
VERIFY_CODE_ERROR("A0214", "验证码错误"),

TOKEN_INVALID("A0230", "token无效或已过期"),
TOKEN_ACCESS_FORBIDDEN("A0231", "token已被禁止访问"),

AUTHORIZED_ERROR("A0300", "访问权限异常"),
ACCESS_UNAUTHORIZED("A0301", "访问未授权"),
FORBIDDEN_OPERATION("A0302", "演示环境禁止新增、修改和删除数据,请本地部署后测试"),


PARAM_ERROR("A0400", "用户请求参数错误"),
RESOURCE_NOT_FOUND("A0401", "请求资源不存在"),
PARAM_IS_NULL("A0410", "请求必填参数为空"),

USER_UPLOAD_FILE_ERROR("A0700", "用户上传文件异常"),
USER_UPLOAD_FILE_TYPE_NOT_MATCH("A0701", "用户上传文件类型不匹配"),
USER_UPLOAD_FILE_SIZE_EXCEEDS("A0702", "用户上传文件太大"),
USER_UPLOAD_IMAGE_SIZE_EXCEEDS("A0703", "用户上传图片太大"),

SYSTEM_EXECUTION_ERROR("B0001", "系统执行出错"),
SYSTEM_EXECUTION_TIMEOUT("B0100", "系统执行超时"),
SYSTEM_ORDER_PROCESSING_TIMEOUT("B0100", "系统订单处理超时"),

SYSTEM_DISASTER_RECOVERY_TRIGGER("B0200", "系统容灾功能被出发"),
FLOW_LIMITING("B0210", "系统限流"),
DEGRADATION("B0220", "系统功能降级"),

SYSTEM_RESOURCE_ERROR("B0300", "系统资源异常"),
SYSTEM_RESOURCE_EXHAUSTION("B0310", "系统资源耗尽"),
SYSTEM_RESOURCE_ACCESS_ERROR("B0320", "系统资源访问异常"),
SYSTEM_READ_DISK_FILE_ERROR("B0321", "系统读取磁盘文件失败"),

CALL_THIRD_PARTY_SERVICE_ERROR("C0001", "调用第三方服务出错"),
MIDDLEWARE_SERVICE_ERROR("C0100", "中间件服务出错"),
INTERFACE_NOT_EXIST("C0113", "接口不存在"),

MESSAGE_SERVICE_ERROR("C0120", "消息服务出错"),
MESSAGE_DELIVERY_ERROR("C0121", "消息投递出错"),
MESSAGE_CONSUMPTION_ERROR("C0122", "消息消费出错"),
MESSAGE_SUBSCRIPTION_ERROR("C0123", "消息订阅出错"),
MESSAGE_GROUP_NOT_FOUND("C0124", "消息分组未查到"),

DATABASE_ERROR("C0300", "数据库服务出错"),
DATABASE_TABLE_NOT_EXIST("C0311", "表不存在"),
DATABASE_COLUMN_NOT_EXIST("C0312", "列不存在"),
DATABASE_DUPLICATE_COLUMN_NAME("C0321", "多表关联中存在多个相同名称的列"),
DATABASE_DEADLOCK("C0331", "数据库死锁"),
DATABASE_PRIMARY_KEY_CONFLICT("C0341", "主键冲突");

private String code;
private String msg;

public static ResultCode getValue(String code) {
for (ResultCode value : values()) {
if (value.getCode().equals(code)) {
return value;
}
}
return SYSTEM_EXECUTION_ERROR; // 默认系统执行错误
}

@Override
public String getCode() {
return code;
}

@Override
public String getMessage() {
return msg;
}

@Override
public String toString() {
return "{" +
"\"code\":\"" + code + '\"' +
", \"msg\":\"" + msg + '\"' +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.jixialunbi.common.utils;

import cn.hutool.json.JSONUtil;
import com.jixialunbi.common.R;
import com.jixialunbi.common.result.ResultCode;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ResponseUtils {

public static void writeErrMsg(HttpServletResponse response, ResultCode resultCode) {
// 根据不同的结果码设置HTTP状态
int status = switch (resultCode) {
case ACCESS_UNAUTHORIZED, TOKEN_INVALID -> HttpStatus.UNAUTHORIZED.value();
case TOKEN_ACCESS_FORBIDDEN -> HttpStatus.FORBIDDEN.value();
default -> HttpStatus.BAD_REQUEST.value();
};
response.setStatus(status);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
try (PrintWriter writer = response.getWriter()) {
String jsonResponse = JSONUtil.toJsonStr(R.error(resultCode));
writer.print(jsonResponse);
writer.flush(); // 确保将响应内容写入到输出流
} catch (IOException e) {
log.error("响应异常处理失败", e);
}
}

}
12 changes: 5 additions & 7 deletions server/src/main/java/com/jixialunbi/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.jixialunbi.security.AuthEntryPointJwt;
import com.jixialunbi.security.AuthTokenFilter;
import com.jixialunbi.security.CustomAccessDeniedHandler;
import com.jixialunbi.security.CAccessDeniedHandler;
import com.jixialunbi.service.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -40,13 +40,10 @@ public class SecurityConfig {
"/swagger-ui.html"
};
private final UserDetailsServiceImpl userDetailsService;

private final CAccessDeniedHandler accessDeniedHandler;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;

@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;

@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
Expand Down Expand Up @@ -80,14 +77,15 @@ public CorsConfiguration corsConfiguration() {
return corsConfiguration;
}


@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity, CorsConfiguration corsConfiguration) throws Exception {
httpSecurity
.cors(cors -> cors.configurationSource(request -> corsConfiguration))
.csrf(e -> e.disable())
.exceptionHandling(exception -> {
exception.accessDeniedHandler(customAccessDeniedHandler);
exception.authenticationEntryPoint(unauthorizedHandler);
exception.authenticationEntryPoint(unauthorizedHandler)
.accessDeniedHandler(accessDeniedHandler);
})
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeHttpRequests(auth ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ public class CategoryController {

@GetMapping("/categories")
public R fetchCategories(@RequestParam(required = false, defaultValue = "1") int page, @RequestParam(required = false, defaultValue = "10") int pageSize) {
try {
return R.ok().data(categoryRepository.findAll());
} catch (Exception e) {
return R.error().message("系统异常");
}
return R.ok().data(categoryRepository.findAll());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,7 @@ public R fetchCategories(
post.setCollected(cn != null && cn.getDeleted() == null);
}
});
try {
return R.ok().data(PageUtil.of(list));
} catch (Exception e) {
return R.error().message("系统异常");
}
return R.ok().data(PageUtil.of(list));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,8 @@ public class CommentController {
public R fetchComments(
@RequestParam(required = false, defaultValue = "1") int page,
@RequestParam(required = false, defaultValue = "10") int pageSize) {
try {
return R.ok().data(commentRepository.findAll());
} catch (Exception e) {
return R.error().message("系统异常");
}
return R.ok().data(commentRepository.findAll());

}

@GetMapping("/post-comments")
Expand All @@ -52,11 +49,8 @@ public R fetchCommentsByPostId(@RequestParam(required = true) long postId) {
map.put("childrens", list.stream().filter(d -> ObjectUtil.equals(d.getParentId(), v.getId())));
return map;
}).toList();
try {
return R.ok().data(result);
} catch (Exception e) {
return R.error().message("系统异常");
}
return R.ok().data(result);

}

@PreAuthorize("hasRole('ROLE_USER')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
@RequestMapping("/api/v1")
public class EmailController {

final String EMAIL_ACTIVE_CODE_KEY = "email_active_code_key";
String html = """
<table
border="0"
Expand Down Expand Up @@ -94,21 +95,15 @@ public class EmailController {
</tr>
</tbody>
</table>""";

@Autowired
HttpSession session;

@Autowired
UserService userService;

@Autowired
UserRepository userRepository;

@Value("${EMAIL_PASS}")
private String EMAIL_PASS;

final String EMAIL_ACTIVE_CODE_KEY = "email_active_code_key";

@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping("/send-email")
public R sendEmail(Principal principal) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,8 @@ public class NotificationController {
@GetMapping("/notifications")
public R fetchNotifications(Principal principal, @RequestParam(required = false, defaultValue = "1") int page, @RequestParam(required = false, defaultValue = "10") int pageSize) {
User author = userService.getByAccount(principal.getName());
try {
return R.ok().data(notificationRepository.findAllByReceiverId(author.getId()));
} catch (Exception e) {
return R.error().message("系统异常");
}
return R.ok().data(notificationRepository.findAllByReceiverId(author.getId()));

}

}
Loading

0 comments on commit 7744db2

Please sign in to comment.