revert: 回退全局响应结果处理器

1.影响 API 文档生成
2.其他已知及未知影响
This commit is contained in:
Charles7c 2023-11-28 20:58:07 +08:00
parent 8c1c4b0144
commit c7a4e32994
13 changed files with 82 additions and 134 deletions

View File

@ -1,70 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.common.handler;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.hutool.core.util.StrUtil;
import top.charles7c.continew.starter.extension.crud.annotation.NoResponseAdvice;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
/**
* 全局响应结果处理器
*
* @author BULL_BCLS
* @since 2023/10/8 20:19
*/
@RestControllerAdvice
@RequiredArgsConstructor
public class GlobalResponseBodyAdviceHandler implements ResponseBodyAdvice<Object> {
private static final String[] EXCLUDE = {"MultipleOpenApiWebMvcResource", "SwaggerConfigResource",};
private final ObjectMapper objectMapper;
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
return !methodParameter.getParameterType().isAssignableFrom(R.class)
&& !methodParameter.hasMethodAnnotation(NoResponseAdvice.class)
&& !StrUtil.equalsAny(methodParameter.getDeclaringClass().getSimpleName(), EXCLUDE);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
if (String.class.equals(returnType.getGenericParameterType())) {
try {
return objectMapper.writeValueAsString(R.ok(body));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
return R.ok(body);
}
}

View File

@ -48,6 +48,7 @@ import top.charles7c.cnadmin.system.model.resp.UserDetailResp;
import top.charles7c.cnadmin.system.service.UserService;
import top.charles7c.continew.starter.cache.redisson.util.RedisUtils;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
import top.charles7c.continew.starter.extension.crud.util.validate.ValidationUtils;
/**
@ -69,7 +70,7 @@ public class AuthController {
@SaIgnore
@Operation(summary = "账号登录", description = "根据账号和密码进行登录认证")
@PostMapping("/account")
public LoginResp accountLogin(@Validated @RequestBody AccountLoginReq loginReq) {
public R<LoginResp> accountLogin(@Validated @RequestBody AccountLoginReq loginReq) {
String captchaKey = RedisUtils.formatKey(CacheConstants.CAPTCHA_KEY_PREFIX, loginReq.getUuid());
String captcha = RedisUtils.get(captchaKey);
ValidationUtils.throwIfBlank(captcha, "验证码已失效");
@ -79,13 +80,13 @@ public class AuthController {
String rawPassword = ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(loginReq.getPassword()));
ValidationUtils.throwIfBlank(rawPassword, "密码解密失败");
String token = loginService.accountLogin(loginReq.getUsername(), rawPassword);
return LoginResp.builder().token(token).build();
return R.ok(LoginResp.builder().token(token).build());
}
@SaIgnore
@Operation(summary = "邮箱登录", description = "根据邮箱和验证码进行登录认证")
@PostMapping("/email")
public LoginResp emailLogin(@Validated @RequestBody EmailLoginReq loginReq) {
public R<LoginResp> emailLogin(@Validated @RequestBody EmailLoginReq loginReq) {
String email = loginReq.getEmail();
String captchaKey = RedisUtils.formatKey(CacheConstants.CAPTCHA_KEY_PREFIX, email);
String captcha = RedisUtils.get(captchaKey);
@ -93,13 +94,13 @@ public class AuthController {
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.delete(captchaKey);
String token = loginService.emailLogin(email);
return LoginResp.builder().token(token).build();
return R.ok(LoginResp.builder().token(token).build());
}
@SaIgnore
@Operation(summary = "手机号登录", description = "根据手机号和验证码进行登录认证")
@PostMapping("/phone")
public LoginResp phoneLogin(@Validated @RequestBody PhoneLoginReq loginReq) {
public R<LoginResp> phoneLogin(@Validated @RequestBody PhoneLoginReq loginReq) {
String phone = loginReq.getPhone();
String captchaKey = RedisUtils.formatKey(CacheConstants.CAPTCHA_KEY_PREFIX, phone);
String captcha = RedisUtils.get(captchaKey);
@ -107,34 +108,36 @@ public class AuthController {
ValidationUtils.throwIfNotEqualIgnoreCase(loginReq.getCaptcha(), captcha, "验证码错误");
RedisUtils.delete(captchaKey);
String token = loginService.phoneLogin(phone);
return LoginResp.builder().token(token).build();
return R.ok(LoginResp.builder().token(token).build());
}
@Operation(summary = "用户退出", description = "注销用户的当前登录")
@Parameter(name = "Authorization", description = "令牌", required = true, example = "Bearer xxxx-xxxx-xxxx-xxxx",
in = ParameterIn.HEADER)
@PostMapping("/logout")
public void logout() {
public R logout() {
StpUtil.logout();
return R.ok();
}
@Log(ignore = true)
@Operation(summary = "获取用户信息", description = "获取登录用户信息")
@GetMapping("/user/info")
public UserInfoResp getUserInfo() {
public R<UserInfoResp> getUserInfo() {
LoginUser loginUser = LoginHelper.getLoginUser();
UserDetailResp userDetailResp = userService.get(loginUser.getId());
UserInfoResp userInfoResp = BeanUtil.copyProperties(userDetailResp, UserInfoResp.class);
userInfoResp.setPermissions(loginUser.getPermissions());
userInfoResp.setRoles(loginUser.getRoleCodes());
return userInfoResp;
return R.ok(userInfoResp);
}
@Log(ignore = true)
@Operation(summary = "获取路由信息", description = "获取登录用户的路由信息")
@GetMapping("/route")
public List<RouteResp> listRoute() {
public R<List<RouteResp>> listRoute() {
Long userId = LoginHelper.getUserId();
return loginService.buildRouteTree(userId);
List<RouteResp> routeTree = loginService.buildRouteTree(userId);
return R.ok(routeTree);
}
}

View File

@ -71,7 +71,7 @@ public class SocialAuthController {
@Operation(summary = "三方账号登录", description = "三方账号登录")
@Parameter(name = "source", description = "来源", example = "gitee", in = ParameterIn.PATH)
@PostMapping("/{source}")
public LoginResp login(@PathVariable String source, @RequestBody AuthCallback callback) {
public R<LoginResp> login(@PathVariable String source, @RequestBody AuthCallback callback) {
if (StpUtil.isLogin()) {
StpUtil.logout();
}
@ -80,7 +80,7 @@ public class SocialAuthController {
ValidationUtils.throwIf(!response.ok(), response.getMsg());
AuthUser authUser = response.getData();
String token = loginService.socialLogin(authUser);
return LoginResp.builder().token(token).build();
return R.ok(LoginResp.builder().token(token).build());
}
private AuthRequest getAuthRequest(String source) {

View File

@ -78,12 +78,12 @@ public class CaptchaController {
@Operation(summary = "获取图片验证码", description = "获取图片验证码Base64编码带图片格式data:image/gif;base64")
@GetMapping("/img")
public CaptchaResp getImageCaptcha() {
public R<CaptchaResp> getImageCaptcha() {
Captcha captcha = graphicCaptchaProperties.getCaptcha();
String uuid = IdUtil.fastUUID();
String captchaKey = RedisUtils.formatKey(CacheConstants.CAPTCHA_KEY_PREFIX, uuid);
RedisUtils.set(captchaKey, captcha.text(), Duration.ofMinutes(captchaProperties.getExpirationInMinutes()));
return CaptchaResp.builder().uuid(uuid).img(captcha.toBase64()).build();
return R.ok(CaptchaResp.builder().uuid(uuid).img(captcha.toBase64()).build());
}
@Operation(summary = "获取邮箱验证码", description = "发送验证码到指定邮箱")

View File

@ -97,39 +97,42 @@ public class CommonController {
@Operation(summary = "查询部门树", description = "查询树结构的部门列表")
@GetMapping("/tree/dept")
public List<Tree<Long>> listDeptTree(DeptQuery query, SortQuery sortQuery) {
return deptService.tree(query, sortQuery, true);
public R<List<Tree<Long>>> listDeptTree(DeptQuery query, SortQuery sortQuery) {
List<Tree<Long>> treeList = deptService.tree(query, sortQuery, true);
return R.ok(treeList);
}
@Operation(summary = "查询菜单树", description = "查询树结构的菜单列表")
@GetMapping("/tree/menu")
public List<Tree<Long>> listMenuTree(MenuQuery query, SortQuery sortQuery) {
return menuService.tree(query, sortQuery, true);
public R<List<Tree<Long>>> listMenuTree(MenuQuery query, SortQuery sortQuery) {
List<Tree<Long>> treeList = menuService.tree(query, sortQuery, true);
return R.ok(treeList);
}
@Operation(summary = "查询角色字典", description = "查询角色字典列表")
@GetMapping("/dict/role")
public List<LabelValueResp<Long>> listRoleDict(RoleQuery query, SortQuery sortQuery) {
public R<List<LabelValueResp<Long>>> listRoleDict(RoleQuery query, SortQuery sortQuery) {
List<RoleResp> list = roleService.list(query, sortQuery);
return roleService.buildDict(list);
List<LabelValueResp<Long>> labelValueList = roleService.buildDict(list);
return R.ok(labelValueList);
}
@Operation(summary = "查询字典", description = "查询字典列表")
@Parameter(name = "code", description = "字典编码", example = "announcement_type", in = ParameterIn.PATH)
@GetMapping("/dict/{code}")
@Cacheable(key = "#code", cacheNames = CacheConstants.DICT_KEY_PREFIX)
public List<LabelValueResp> listDict(@PathVariable String code) {
public R<List<LabelValueResp>> listDict(@PathVariable String code) {
Optional<Class<?>> enumClass = this.getEnumClassByName(code);
return enumClass.map(this::listEnumDict).orElseGet(() -> dictItemService.listByDictCode(code));
return R.ok(enumClass.map(this::listEnumDict).orElseGet(() -> dictItemService.listByDictCode(code)));
}
@SaIgnore
@Operation(summary = "查询参数", description = "查询参数")
@GetMapping("/option")
@Cacheable(cacheNames = CacheConstants.OPTION_KEY_PREFIX)
public List<LabelValueResp> listOption(@Validated OptionQuery query) {
return optionService.list(query).stream().map(option -> new LabelValueResp(option.getCode(),
StrUtil.nullToDefault(option.getValue(), option.getDefaultValue()))).collect(Collectors.toList());
public R<List<LabelValueResp>> listOption(@Validated OptionQuery query) {
return R.ok(optionService.list(query).stream().map(option -> new LabelValueResp(option.getCode(),
StrUtil.nullToDefault(option.getValue(), option.getDefaultValue()))).collect(Collectors.toList()));
}
/**

View File

@ -38,6 +38,7 @@ import top.charles7c.cnadmin.monitor.model.resp.DashboardPopularModuleResp;
import top.charles7c.cnadmin.monitor.model.resp.DashboardTotalResp;
import top.charles7c.cnadmin.monitor.service.DashboardService;
import top.charles7c.cnadmin.system.model.resp.DashboardAnnouncementResp;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
import top.charles7c.continew.starter.extension.crud.util.validate.ValidationUtils;
/**
@ -58,33 +59,33 @@ public class DashboardController {
@Operation(summary = "查询总计信息", description = "查询总计信息")
@GetMapping("/total")
public DashboardTotalResp getTotal() {
return dashboardService.getTotal();
public R<DashboardTotalResp> getTotal() {
return R.ok(dashboardService.getTotal());
}
@Operation(summary = "查询访问趋势信息", description = "查询访问趋势信息")
@Parameter(name = "days", description = "日期数", example = "30", in = ParameterIn.PATH)
@GetMapping("/access/trend/{days}")
public List<DashboardAccessTrendResp> listAccessTrend(@PathVariable Integer days) {
public R<List<DashboardAccessTrendResp>> listAccessTrend(@PathVariable Integer days) {
ValidationUtils.throwIf(7 != days && 30 != days, "仅支持查询近 7/30 天访问趋势信息");
return dashboardService.listAccessTrend(days);
return R.ok(dashboardService.listAccessTrend(days));
}
@Operation(summary = "查询热门模块列表", description = "查询热门模块列表")
@GetMapping("/popular/module")
public List<DashboardPopularModuleResp> listPopularModule() {
return dashboardService.listPopularModule();
public R<List<DashboardPopularModuleResp>> listPopularModule() {
return R.ok(dashboardService.listPopularModule());
}
@Operation(summary = "查询访客地域分布信息", description = "查询访客地域分布信息")
@GetMapping("/geo/distribution")
public DashboardGeoDistributionResp getGeoDistribution() {
return dashboardService.getGeoDistribution();
public R<DashboardGeoDistributionResp> getGeoDistribution() {
return R.ok(dashboardService.getGeoDistribution());
}
@Operation(summary = "查询公告列表", description = "查询公告列表")
@GetMapping("/announcement")
public List<DashboardAnnouncementResp> listAnnouncement() {
return dashboardService.listAnnouncement();
public R<List<DashboardAnnouncementResp>> listAnnouncement() {
return R.ok(dashboardService.listAnnouncement());
}
}

View File

@ -40,6 +40,7 @@ import top.charles7c.cnadmin.monitor.model.resp.SystemLogResp;
import top.charles7c.cnadmin.monitor.service.LogService;
import top.charles7c.continew.starter.extension.crud.model.query.PageQuery;
import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
/**
* 日志管理 API
@ -58,29 +59,33 @@ public class LogController {
@Log(module = "登录日志")
@Operation(summary = "分页查询登录日志列表", description = "分页查询登录日志列表")
@GetMapping("/login")
public PageDataResp<LoginLogResp> page(LoginLogQuery query, @Validated PageQuery pageQuery) {
return logService.page(query, pageQuery);
public R<PageDataResp<LoginLogResp>> page(LoginLogQuery query, @Validated PageQuery pageQuery) {
PageDataResp<LoginLogResp> pageData = logService.page(query, pageQuery);
return R.ok(pageData);
}
@Log(module = "操作日志")
@Operation(summary = "分页查询操作日志列表", description = "分页查询操作日志列表")
@GetMapping("/operation")
public PageDataResp<OperationLogResp> page(OperationLogQuery query, @Validated PageQuery pageQuery) {
return logService.page(query, pageQuery);
public R<PageDataResp<OperationLogResp>> page(OperationLogQuery query, @Validated PageQuery pageQuery) {
PageDataResp<OperationLogResp> pageData = logService.page(query, pageQuery);
return R.ok(pageData);
}
@Log(module = "系统日志")
@Operation(summary = "分页查询系统日志列表", description = "分页查询系统日志列表")
@GetMapping("/system")
public PageDataResp<SystemLogResp> page(SystemLogQuery query, @Validated PageQuery pageQuery) {
return logService.page(query, pageQuery);
public R<PageDataResp<SystemLogResp>> page(SystemLogQuery query, @Validated PageQuery pageQuery) {
PageDataResp<SystemLogResp> pageData = logService.page(query, pageQuery);
return R.ok(pageData);
}
@Log(module = "系统日志")
@Operation(summary = "查看系统日志详情", description = "查看系统日志详情")
@Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH)
@GetMapping("/system/{id}")
public SystemLogDetailResp get(@PathVariable Long id) {
return logService.get(id);
public R<SystemLogDetailResp> get(@PathVariable Long id) {
SystemLogDetailResp detail = logService.get(id);
return R.ok(detail);
}
}

View File

@ -54,8 +54,9 @@ public class OnlineUserController {
@Operation(summary = "分页查询列表", description = "分页查询列表")
@SaCheckPermission("monitor:online:user:list")
@GetMapping
public PageDataResp<OnlineUserResp> page(OnlineUserQuery query, @Validated PageQuery pageQuery) {
return onlineUserService.page(query, pageQuery);
public R<PageDataResp<OnlineUserResp>> page(OnlineUserQuery query, @Validated PageQuery pageQuery) {
PageDataResp<OnlineUserResp> pageData = onlineUserService.page(query, pageQuery);
return R.ok(pageData);
}
@Operation(summary = "强退在线用户", description = "强退在线用户")

View File

@ -27,7 +27,6 @@ import top.charles7c.cnadmin.system.model.resp.DictResp;
import top.charles7c.cnadmin.system.service.DictService;
import top.charles7c.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.charles7c.continew.starter.extension.crud.base.BaseController;
import top.charles7c.continew.starter.extension.crud.enums.Api;
/**
* 字典管理 API

View File

@ -56,9 +56,10 @@ public class MessageController {
@Operation(summary = "分页查询列表", description = "分页查询列表")
@GetMapping
public PageDataResp<MessageResp> page(MessageQuery query, @Validated PageQuery pageQuery) {
public R<PageDataResp<MessageResp>> page(MessageQuery query, @Validated PageQuery pageQuery) {
query.setUserId(LoginHelper.getUserId());
return baseService.page(query, pageQuery);
PageDataResp<MessageResp> pageData = baseService.page(query, pageQuery);
return R.ok(pageData);
}
@Operation(summary = "删除数据", description = "删除数据")
@ -72,15 +73,16 @@ public class MessageController {
@Operation(summary = "标记已读", description = "将消息标记为已读状态")
@Parameter(name = "ids", description = "消息ID列表", example = "1,2", in = ParameterIn.QUERY)
@PatchMapping("/read")
public void readMessage(@RequestParam(required = false) List<Long> ids) {
public R readMessage(@RequestParam(required = false) List<Long> ids) {
messageUserService.readMessage(ids);
return R.ok();
}
@Log(ignore = true)
@Operation(summary = "查询未读消息数量", description = "查询当前用户的未读消息数量")
@Parameter(name = "isDetail", description = "是否查询详情", example = "true", in = ParameterIn.QUERY)
@GetMapping("/unread")
public MessageUnreadResp countUnreadMessage(@RequestParam(required = false) Boolean detail) {
return messageUserService.countUnreadMessageByUserId(LoginHelper.getUserId(), detail);
public R<MessageUnreadResp> countUnreadMessage(@RequestParam(required = false) Boolean detail) {
return R.ok(messageUserService.countUnreadMessageByUserId(LoginHelper.getUserId(), detail));
}
}

View File

@ -33,6 +33,7 @@ import top.charles7c.cnadmin.system.model.req.OptionReq;
import top.charles7c.cnadmin.system.model.req.OptionResetValueReq;
import top.charles7c.cnadmin.system.model.resp.OptionResp;
import top.charles7c.cnadmin.system.service.OptionService;
import top.charles7c.continew.starter.extension.crud.model.resp.R;
/**
* 参数管理 API
@ -51,21 +52,23 @@ public class OptionController {
@Operation(summary = "查询参数列表", description = "查询参数列表")
@SaCheckPermission("system:config:list")
@GetMapping
public List<OptionResp> list(@Validated OptionQuery query) {
return optionService.list(query);
public R<List<OptionResp>> list(@Validated OptionQuery query) {
return R.ok(optionService.list(query));
}
@Operation(summary = "修改参数", description = "修改参数")
@SaCheckPermission("system:config:update")
@PatchMapping
public void update(@Validated @RequestBody List<OptionReq> req) {
public R update(@Validated @RequestBody List<OptionReq> req) {
optionService.update(req);
return R.ok();
}
@Operation(summary = "重置参数", description = "重置参数")
@SaCheckPermission("system:config:reset")
@PatchMapping("/value")
public void resetValue(@Validated @RequestBody OptionResetValueReq req) {
public R resetValue(@Validated @RequestBody OptionResetValueReq req) {
optionService.resetValue(req);
return R.ok();
}
}

View File

@ -139,15 +139,16 @@ public class UserCenterController {
@Operation(summary = "查询绑定的三方账号", description = "查询绑定的三方账号")
@GetMapping("/social")
public List<UserSocialBindResp> listSocialBind() {
public R<List<UserSocialBindResp>> listSocialBind() {
List<UserSocialDO> userSocialList = userSocialService.listByUserId(LoginHelper.getUserId());
return userSocialList.stream().map(userSocial -> {
List<UserSocialBindResp> userSocialBindList = userSocialList.stream().map(userSocial -> {
String source = userSocial.getSource();
UserSocialBindResp userSocialBind = new UserSocialBindResp();
userSocialBind.setSource(source);
userSocialBind.setDescription(SocialSourceEnum.valueOf(source).getDescription());
return userSocialBind;
}).collect(Collectors.toList());
return R.ok(userSocialBindList);
}
@Operation(summary = "绑定三方账号", description = "绑定三方账号")

View File

@ -62,8 +62,8 @@ public class GeneratorController {
@Operation(summary = "分页查询数据表", description = "分页查询数据表")
@SaCheckPermission("tool:generator:list")
@GetMapping("/table")
public PageDataResp<TableResp> pageTable(TableQuery query, @Validated PageQuery pageQuery) throws SQLException {
return generatorService.pageTable(query, pageQuery);
public R<PageDataResp<TableResp>> pageTable(TableQuery query, @Validated PageQuery pageQuery) throws SQLException {
return R.ok(generatorService.pageTable(query, pageQuery));
}
@Operation(summary = "查询字段配置列表", description = "查询字段配置列表")
@ -71,17 +71,17 @@ public class GeneratorController {
@Parameter(name = "requireSync", description = "是否需要同步", example = "false", in = ParameterIn.QUERY)
@SaCheckPermission("tool:generator:list")
@GetMapping("/field/{tableName}")
public List<FieldConfigDO> listFieldConfig(@PathVariable String tableName,
public R<List<FieldConfigDO>> listFieldConfig(@PathVariable String tableName,
@RequestParam(required = false, defaultValue = "false") Boolean requireSync) {
return generatorService.listFieldConfig(tableName, requireSync);
return R.ok(generatorService.listFieldConfig(tableName, requireSync));
}
@Operation(summary = "查询生成配置信息", description = "查询生成配置信息")
@Parameter(name = "tableName", description = "表名称", required = true, example = "sys_user", in = ParameterIn.PATH)
@SaCheckPermission("tool:generator:list")
@GetMapping("/config/{tableName}")
public GenConfigDO getGenConfig(@PathVariable String tableName) throws SQLException {
return generatorService.getGenConfig(tableName);
public R<GenConfigDO> getGenConfig(@PathVariable String tableName) throws SQLException {
return R.ok(generatorService.getGenConfig(tableName));
}
@Operation(summary = "保存配置信息", description = "保存配置信息")