完成错误码的后端代码

This commit is contained in:
YunaiV 2021-04-21 01:04:48 +08:00
parent 3580b416bc
commit 6984eb5db1
31 changed files with 846 additions and 525 deletions

View File

@ -0,0 +1,12 @@
###
POST {{baseUrl}}/inra/error-code/create
Authorization: Bearer {{token}}
Content-Type:application/json
{
"code": 200,
"message": "成功",
"group": "test",
"type": 1
}

View File

@ -0,0 +1,89 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode;
import cn.iocoder.dashboard.common.pojo.CommonResult;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.excel.core.util.ExcelUtils;
import cn.iocoder.dashboard.framework.logger.operatelog.core.annotations.OperateLog;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.*;
import cn.iocoder.dashboard.modules.infra.convert.errorcode.InfErrorCodeConvert;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import cn.iocoder.dashboard.modules.infra.service.errorcode.InfErrorCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import static cn.iocoder.dashboard.common.pojo.CommonResult.success;
import static cn.iocoder.dashboard.framework.logger.operatelog.core.enums.OperateTypeEnum.EXPORT;
@Api(tags = "错误码")
@RestController
@RequestMapping("/infra/error-code")
@Validated
public class InfErrorCodeController {
@Resource
private InfErrorCodeService errorCodeService;
@PostMapping("/create")
@ApiOperation("创建错误码")
@PreAuthorize("@ss.hasPermission('infra:error-code:create')")
public CommonResult<Long> createErrorCode(@Valid @RequestBody InfErrorCodeCreateReqVO createReqVO) {
return success(errorCodeService.createErrorCode(createReqVO));
}
@PutMapping("/update")
@ApiOperation("更新错误码")
@PreAuthorize("@ss.hasPermission('infra:error-code:update')")
public CommonResult<Boolean> updateErrorCode(@Valid @RequestBody InfErrorCodeUpdateReqVO updateReqVO) {
errorCodeService.updateErrorCode(updateReqVO);
return success(true);
}
@DeleteMapping("/delete")
@ApiOperation("删除错误码")
@ApiImplicitParam(name = "id", value = "编号", required = true)
@PreAuthorize("@ss.hasPermission('infra:error-code:delete')")
public CommonResult<Boolean> deleteErrorCode(@RequestParam("id") Long id) {
errorCodeService.deleteErrorCode(id);
return success(true);
}
@GetMapping("/get")
@ApiOperation("获得错误码")
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
@PreAuthorize("@ss.hasPermission('infra:error-code:query')")
public CommonResult<InfErrorCodeRespVO> getErrorCode(@RequestParam("id") Long id) {
InfErrorCodeDO errorCode = errorCodeService.getErrorCode(id);
return success(InfErrorCodeConvert.INSTANCE.convert(errorCode));
}
@GetMapping("/page")
@ApiOperation("获得错误码分页")
@PreAuthorize("@ss.hasPermission('infra:error-code:query')")
public CommonResult<PageResult<InfErrorCodeRespVO>> getErrorCodePage(@Valid InfErrorCodePageReqVO pageVO) {
PageResult<InfErrorCodeDO> pageResult = errorCodeService.getErrorCodePage(pageVO);
return success(InfErrorCodeConvert.INSTANCE.convertPage(pageResult));
}
@GetMapping("/export-excel")
@ApiOperation("导出错误码 Excel")
@PreAuthorize("@ss.hasPermission('infra:error-code:export')")
@OperateLog(type = EXPORT)
public void exportErrorCodeExcel(@Valid InfErrorCodeExportReqVO exportReqVO,
HttpServletResponse response) throws IOException {
List<InfErrorCodeDO> list = errorCodeService.getErrorCodeList(exportReqVO);
// 导出 Excel
List<InfErrorCodeExcelVO> datas = InfErrorCodeConvert.INSTANCE.convertList02(list);
ExcelUtils.write(response, "错误码.xls", "数据", InfErrorCodeExcelVO.class, datas);
}
}

View File

@ -0,0 +1,30 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* 错误码 Base VO提供给添加修改详细的子 VO 使用
* 如果子 VO 存在差异的字段请不要添加到这里影响 Swagger 文档生成
*/
@Data
public class InfErrorCodeBaseVO {
@ApiModelProperty(value = "应用名", required = true, example = "dashboard")
@NotNull(message = "应用名不能为空")
private String applicationName;
@ApiModelProperty(value = "错误码编码", required = true, example = "1234")
@NotNull(message = "错误码编码不能为空")
private Integer code;
@ApiModelProperty(value = "错误码错误提示", required = true, example = "帅气")
@NotNull(message = "错误码错误提示不能为空")
private String message;
@ApiModelProperty(value = "备注", example = "哈哈哈")
private String memo;
}

View File

@ -0,0 +1,14 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@ApiModel("错误码创建 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class InfErrorCodeCreateReqVO extends InfErrorCodeBaseVO {
}

View File

@ -0,0 +1,42 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import cn.iocoder.dashboard.framework.excel.core.annotations.DictFormat;
import cn.iocoder.dashboard.framework.excel.core.convert.DictConvert;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import java.util.Date;
import static cn.iocoder.dashboard.modules.system.enums.dict.SysDictTypeEnum.INF_ERROR_CODE_TYPE;
/**
* 错误码 Excel VO
*
* @author 芋道源码
*/
@Data
public class InfErrorCodeExcelVO {
@ExcelProperty("错误码编号")
private Long id;
@ExcelProperty(value = "错误码类型", converter = DictConvert.class)
@DictFormat(INF_ERROR_CODE_TYPE)
private Integer type;
@ExcelProperty("应用名")
private String applicationName;
@ExcelProperty("错误码编码")
private Integer code;
@ExcelProperty("错误码错误提示")
private String message;
@ExcelProperty("备注")
private String memo;
@ExcelProperty("创建时间")
private Date createTime;
}

View File

@ -0,0 +1,36 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import static cn.iocoder.dashboard.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@ApiModel(value = "错误码 Excel 导出 Request VO", description = "参数和 InfErrorCodePageReqVO 是一致的")
@Data
public class InfErrorCodeExportReqVO {
@ApiModelProperty(value = "错误码类型", example = "1")
private Integer type;
@ApiModelProperty(value = "应用名", example = "dashboard")
private String applicationName;
@ApiModelProperty(value = "错误码编码", example = "1234")
private Integer code;
@ApiModelProperty(value = "错误码错误提示", example = "帅气")
private String message;
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
@ApiModelProperty(value = "开始创建时间")
private Date beginCreateTime;
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
@ApiModelProperty(value = "结束创建时间")
private Date endCreateTime;
}

View File

@ -0,0 +1,41 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import cn.iocoder.dashboard.common.pojo.PageParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import static cn.iocoder.dashboard.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@ApiModel("错误码分页 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class InfErrorCodePageReqVO extends PageParam {
@ApiModelProperty(value = "错误码类型", example = "1", notes = "参见 SysErrorCodeTypeEnum 枚举类")
private Integer type;
@ApiModelProperty(value = "应用名", example = "dashboard")
private String applicationName;
@ApiModelProperty(value = "错误码编码", example = "1234")
private Integer code;
@ApiModelProperty(value = "错误码错误提示", example = "帅气")
private String message;
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
@ApiModelProperty(value = "开始创建时间")
private Date beginCreateTime;
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
@ApiModelProperty(value = "结束创建时间")
private Date endCreateTime;
}

View File

@ -0,0 +1,26 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.Date;
@ApiModel("错误码 Response VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class InfErrorCodeRespVO extends InfErrorCodeBaseVO {
@ApiModelProperty(value = "错误码编号", required = true, example = "1024")
private Long id;
@ApiModelProperty(value = "错误码类型", required = true, example = "1", notes = "参见 SysErrorCodeTypeEnum 枚举类")
private Integer type;
@ApiModelProperty(value = "创建时间", required = true)
private Date createTime;
}

View File

@ -0,0 +1,21 @@
package cn.iocoder.dashboard.modules.infra.controller.errorcode.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.validation.constraints.NotNull;
@ApiModel("错误码更新 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class InfErrorCodeUpdateReqVO extends InfErrorCodeBaseVO {
@ApiModelProperty(value = "错误码编号", required = true, example = "1024")
@NotNull(message = "错误码编号不能为空")
private Long id;
}

View File

@ -0,0 +1,42 @@
package cn.iocoder.dashboard.modules.infra.convert.errorcode;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeRespDTO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeCreateReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeExcelVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeRespVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeUpdateReqVO;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 错误码 Convert
*
* @author 芋道源码
*/
@Mapper
public interface InfErrorCodeConvert {
InfErrorCodeConvert INSTANCE = Mappers.getMapper(InfErrorCodeConvert.class);
InfErrorCodeDO convert(InfErrorCodeCreateReqVO bean);
InfErrorCodeDO convert(InfErrorCodeUpdateReqVO bean);
InfErrorCodeRespVO convert(InfErrorCodeDO bean);
List<InfErrorCodeRespVO> convertList(List<InfErrorCodeDO> list);
PageResult<InfErrorCodeRespVO> convertPage(PageResult<InfErrorCodeDO> page);
List<InfErrorCodeExcelVO> convertList02(List<InfErrorCodeDO> list);
InfErrorCodeDO convert(ErrorCodeAutoGenerateReqDTO bean);
List<ErrorCodeRespDTO> convertList03(List<InfErrorCodeDO> list);
}

View File

@ -1,38 +0,0 @@
package cn.iocoder.dashboard.modules.infra.convert.errorcode;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeRespDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodeCreateDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodeUpdateDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.vo.ErrorCodeVO;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper(unmappedSourcePolicy = ReportingPolicy.IGNORE)
public interface SysErrorCodeConvert {
SysErrorCodeConvert INSTANCE = Mappers.getMapper(SysErrorCodeConvert.class);
ErrorCodeVO convert (InfErrorCodeDO bean);
List<ErrorCodeVO> convertList(List<InfErrorCodeDO> list);
@Mapping(source = "records", target = "list")
PageResult<ErrorCodeVO> convertPage(IPage<InfErrorCodeDO> page);
InfErrorCodeDO convert (ErrorCodeCreateDTO bean);
InfErrorCodeDO convert (ErrorCodeUpdateDTO bean);
InfErrorCodeDO convert(ErrorCodeAutoGenerateReqDTO bean);
List<ErrorCodeRespDTO> convertList02(List<InfErrorCodeDO> list);
}

View File

@ -1,7 +1,7 @@
package cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode;
import cn.iocoder.dashboard.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.dashboard.modules.system.enums.errorcode.SysErrorCodeTypeEnum;
import cn.iocoder.dashboard.modules.infra.enums.errorcode.InfErrorCodeTypeEnum;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@ -27,7 +27,7 @@ public class InfErrorCodeDO extends BaseDO {
/**
* 错误码类型
*
* 枚举 {@link SysErrorCodeTypeEnum}
* 枚举 {@link InfErrorCodeTypeEnum}
*/
private Integer type;
/**

View File

@ -1,12 +1,12 @@
package cn.iocoder.dashboard.modules.infra.dal.mysql.errorcode;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.dashboard.framework.mybatis.core.query.QueryWrapperX;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodePageDTO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeExportReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodePageReqVO;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import java.util.Collection;
@ -14,12 +14,26 @@ import java.util.Date;
import java.util.List;
@Mapper
public interface InfErrorCodeMapper extends BaseMapper<InfErrorCodeDO> {
public interface InfErrorCodeMapper extends BaseMapperX<InfErrorCodeDO> {
default IPage<InfErrorCodeDO> selectPage(ErrorCodePageDTO pageDTO) {
return selectPage(new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize()),
new QueryWrapperX<InfErrorCodeDO>().likeIfPresent("`group`", pageDTO.getGroup())
.eqIfPresent("code", pageDTO.getCode()).likeIfPresent("message", pageDTO.getMessage()));
default PageResult<InfErrorCodeDO> selectPage(InfErrorCodePageReqVO reqVO) {
return selectPage(reqVO, new QueryWrapperX<InfErrorCodeDO>()
.eqIfPresent("type", reqVO.getType())
.likeIfPresent("application_name", reqVO.getApplicationName())
.eqIfPresent("code", reqVO.getCode())
.likeIfPresent("message", reqVO.getMessage())
.betweenIfPresent("create_time", reqVO.getBeginCreateTime(), reqVO.getEndCreateTime())
.orderByAsc("application_name", "code"));
}
default List<InfErrorCodeDO> selectList(InfErrorCodeExportReqVO reqVO) {
return selectList(new QueryWrapperX<InfErrorCodeDO>()
.eqIfPresent("type", reqVO.getType())
.likeIfPresent("application_name", reqVO.getApplicationName())
.eqIfPresent("code", reqVO.getCode())
.likeIfPresent("message", reqVO.getMessage())
.betweenIfPresent("create_time", reqVO.getBeginCreateTime(), reqVO.getEndCreateTime())
.orderByAsc("application_name", "code"));
}
default List<InfErrorCodeDO> selectListByCodes(Collection<Integer> codes) {

View File

@ -30,4 +30,9 @@ public interface InfErrorCodeConstants {
// ========== 文件 1001003000 ==========
ErrorCode FILE_NOT_EXISTS = new ErrorCode(1001003000, "文件不存在");
// ========== 错误码模块 1001004000 ==========
ErrorCode ERROR_CODE_NOT_EXISTS = new ErrorCode(1001004000, "错误码不存在");
ErrorCode ERROR_CODE_DUPLICATE = new ErrorCode(1001004001, "已经存在编码为【{}}】的错误码");
ErrorCode ERROR_CAN_NOT_UPDATE_SYSTEM_TYPE_ERROR = new ErrorCode(1001004002, "不能修改类型为系统内置的错误码");
}

View File

@ -1,4 +1,4 @@
package cn.iocoder.dashboard.modules.system.enums.errorcode;
package cn.iocoder.dashboard.modules.infra.enums.errorcode;
import cn.iocoder.dashboard.common.core.IntArrayValuable;
import lombok.AllArgsConstructor;
@ -13,7 +13,7 @@ import java.util.Arrays;
*/
@AllArgsConstructor
@Getter
public enum SysErrorCodeTypeEnum implements IntArrayValuable {
public enum InfErrorCodeTypeEnum implements IntArrayValuable {
/**
* 自动生成
@ -24,7 +24,7 @@ public enum SysErrorCodeTypeEnum implements IntArrayValuable {
*/
MANUAL_OPERATION(2);
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(SysErrorCodeTypeEnum::getType).toArray();
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(InfErrorCodeTypeEnum::getType).toArray();
/**
* 类型

View File

@ -0,0 +1,67 @@
package cn.iocoder.dashboard.modules.infra.service.errorcode;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.errorcode.core.service.ErrorCodeFrameworkService;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeCreateReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeExportReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodePageReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeUpdateReqVO;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import javax.validation.Valid;
import java.util.List;
/**
* 错误码 Service 接口
*
* @author 芋道源码
*/
public interface InfErrorCodeService extends ErrorCodeFrameworkService {
/**
* 创建错误码
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createErrorCode(@Valid InfErrorCodeCreateReqVO createReqVO);
/**
* 更新错误码
*
* @param updateReqVO 更新信息
*/
void updateErrorCode(@Valid InfErrorCodeUpdateReqVO updateReqVO);
/**
* 删除错误码
*
* @param id 编号
*/
void deleteErrorCode(Long id);
/**
* 获得错误码
*
* @param id 编号
* @return 错误码
*/
InfErrorCodeDO getErrorCode(Long id);
/**
* 获得错误码分页
*
* @param pageReqVO 分页查询
* @return 错误码分页
*/
PageResult<InfErrorCodeDO> getErrorCodePage(InfErrorCodePageReqVO pageReqVO);
/**
* 获得错误码列表, 用于 Excel 导出
*
* @param exportReqVO 查询条件
* @return 错误码列表
*/
List<InfErrorCodeDO> getErrorCodeList(InfErrorCodeExportReqVO exportReqVO);
}

View File

@ -0,0 +1,173 @@
package cn.iocoder.dashboard.modules.infra.service.errorcode.impl;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeRespDTO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeCreateReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeExportReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodePageReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeUpdateReqVO;
import cn.iocoder.dashboard.modules.infra.convert.errorcode.InfErrorCodeConvert;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import cn.iocoder.dashboard.modules.infra.dal.mysql.errorcode.InfErrorCodeMapper;
import cn.iocoder.dashboard.modules.infra.enums.errorcode.InfErrorCodeTypeEnum;
import cn.iocoder.dashboard.modules.infra.service.errorcode.InfErrorCodeService;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static cn.iocoder.dashboard.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.dashboard.modules.infra.enums.InfErrorCodeConstants.ERROR_CODE_DUPLICATE;
import static cn.iocoder.dashboard.modules.infra.enums.InfErrorCodeConstants.ERROR_CODE_NOT_EXISTS;
import static cn.iocoder.dashboard.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.dashboard.util.collection.CollectionUtils.convertSet;
/**
* 错误码 Service 实现类
*/
@Service
@Validated
@Slf4j
public class InfErrorCodeServiceImpl implements InfErrorCodeService {
@Resource
private InfErrorCodeMapper errorCodeMapper;
@Override
public Long createErrorCode(InfErrorCodeCreateReqVO createReqVO) {
// 校验 code 重复
validateCodeDuplicate(createReqVO.getCode(), null);
// 插入
InfErrorCodeDO errorCode = InfErrorCodeConvert.INSTANCE.convert(createReqVO)
.setType(InfErrorCodeTypeEnum.MANUAL_OPERATION.getType());
errorCodeMapper.insert(errorCode);
// 返回
return errorCode.getId();
}
@Override
public void updateErrorCode(InfErrorCodeUpdateReqVO updateReqVO) {
// 校验存在
this.validateErrorCodeExists(updateReqVO.getId());
// 校验 code 重复
validateCodeDuplicate(updateReqVO.getCode(), updateReqVO.getId());
// 更新
InfErrorCodeDO updateObj = InfErrorCodeConvert.INSTANCE.convert(updateReqVO)
.setType(InfErrorCodeTypeEnum.MANUAL_OPERATION.getType());
errorCodeMapper.updateById(updateObj);
}
@Override
public void deleteErrorCode(Long id) {
// 校验存在
this.validateErrorCodeExists(id);
// 删除
errorCodeMapper.deleteById(id);
}
/**
* 校验错误码的唯一字段是否重复
*
* 是否存在相同编码的错误码
*
* @param code 错误码编码
* @param id 错误码编号
*/
@VisibleForTesting
public void validateCodeDuplicate(Integer code, Long id) {
InfErrorCodeDO errorCodeDO = errorCodeMapper.selectByCode(code);
if (errorCodeDO == null) {
return;
}
// 如果 id 为空说明不用比较是否为相同 id 的错误码
if (id == null) {
throw exception(ERROR_CODE_DUPLICATE);
}
if (!errorCodeDO.getId().equals(id)) {
throw exception(ERROR_CODE_DUPLICATE);
}
}
@VisibleForTesting
public void validateErrorCodeExists(Long id) {
if (errorCodeMapper.selectById(id) == null) {
throw exception(ERROR_CODE_NOT_EXISTS);
}
}
@Override
public InfErrorCodeDO getErrorCode(Long id) {
return errorCodeMapper.selectById(id);
}
@Override
public PageResult<InfErrorCodeDO> getErrorCodePage(InfErrorCodePageReqVO pageReqVO) {
return errorCodeMapper.selectPage(pageReqVO);
}
@Override
public List<InfErrorCodeDO> getErrorCodeList(InfErrorCodeExportReqVO exportReqVO) {
return errorCodeMapper.selectList(exportReqVO);
}
@Override
@Transactional
public void autoGenerateErrorCodes(List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs) {
if (CollUtil.isEmpty(autoGenerateDTOs)) {
return;
}
// 获得错误码
List<InfErrorCodeDO> errorCodeDOs = errorCodeMapper.selectListByCodes(
convertSet(autoGenerateDTOs, ErrorCodeAutoGenerateReqDTO::getCode));
Map<Integer, InfErrorCodeDO> errorCodeDOMap = convertMap(errorCodeDOs, InfErrorCodeDO::getCode);
// 遍历 autoGenerateBOs 数组逐个插入或更新考虑到每次量级不大就不走批量了
autoGenerateDTOs.forEach(autoGenerateDTO -> {
InfErrorCodeDO errorCodeDO = errorCodeDOMap.get(autoGenerateDTO.getCode());
// 不存在则进行新增
if (errorCodeDO == null) {
errorCodeDO = InfErrorCodeConvert.INSTANCE.convert(autoGenerateDTO)
.setType(InfErrorCodeTypeEnum.AUTO_GENERATION.getType());
errorCodeMapper.insert(errorCodeDO);
return;
}
// 存在则进行更新更新有三个前置条件
// 条件 1. 只更新自动生成的错误码 Type ErrorCodeTypeEnum.AUTO_GENERATION
if (!InfErrorCodeTypeEnum.AUTO_GENERATION.getType().equals(errorCodeDO.getType())) {
return;
}
// 条件 2. 分组 group 必须匹配避免存在错误码冲突的情况
if (!autoGenerateDTO.getApplicationName().equals(errorCodeDO.getApplicationName())) {
log.error("[autoGenerateErrorCodes][自动创建({}/{}) 错误码失败,数据库中已经存在({}/{})]",
autoGenerateDTO.getCode(), autoGenerateDTO.getApplicationName(),
errorCodeDO.getCode(), errorCodeDO.getApplicationName());
return;
}
// 条件 3. 错误提示语存在差异
if (autoGenerateDTO.getMessage().equals(errorCodeDO.getMessage())) {
return;
}
// 最终匹配进行更新
errorCodeMapper.updateById(new InfErrorCodeDO().setId(errorCodeDO.getId()).setMessage(autoGenerateDTO.getMessage()));
});
}
@Override
public List<ErrorCodeRespDTO> getErrorCodeList(String applicationName, Date minUpdateTime) {
List<InfErrorCodeDO> errorCodeDOs = errorCodeMapper.selectListByApplicationNameAndUpdateTimeGt(
applicationName, minUpdateTime);
return InfErrorCodeConvert.INSTANCE.convertList03(errorCodeDOs);
}
}

View File

@ -1,42 +0,0 @@
### list-group
GET http://localhost:48080/api/system/error-code/list-group
Authorization: Bearer {{token}}
Content-Type: application/x-www-form-urlencoded
group=test&minUpdateTime=2021-03-14 14:37:47
###
GET http://localhost:48080/api/system/error-code/query
Authorization: Bearer {{token}}
Content-Type: application/x-www-form-urlencoded
errorCodeId=350
###
POST http://localhost:48080/api/system/error-code/generate
Authorization: Bearer {{token}}
[
{
"code": 202,
"message": "成功1",
"group": "test1"
}
]
###
POST http://localhost:48080/api/system/error-code/create
Authorization: Bearer {{token}}
Content-Type:application/json
{
"code": 200,
"message": "成功",
"group": "test",
"type": 1
}

View File

@ -1,99 +0,0 @@
package cn.iocoder.dashboard.modules.system.controller.errorcode;
import cn.iocoder.dashboard.common.pojo.CommonResult;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodeCreateDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodePageDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodeUpdateDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.vo.ErrorCodeVO;
import cn.iocoder.dashboard.modules.system.service.errorcode.impl.ErrorCodeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import static cn.iocoder.dashboard.common.pojo.CommonResult.success;
@Api(tags = "错误码")
@RestController
@RequestMapping("/system/error-code")
public class ErrorCodeController {
@Resource
private ErrorCodeServiceImpl errorCodeService;
/**
* 创建错误码
*
* @param createDTO 创建错误码 DTO
* @return 错误码编号
*/
@ApiOperation("创建错误码")
@PostMapping("/create")
public CommonResult<Integer> createErrorCode(@RequestBody ErrorCodeCreateDTO createDTO) {
return success(errorCodeService.createErrorCode(createDTO).getId());
}
/**
* 更新错误码
*
* @param updateDTO 更新错误码 DTO
*/
@ApiOperation("更新错误码")
@PatchMapping("/update")
public CommonResult<Boolean> updateErrorCode(@RequestBody ErrorCodeUpdateDTO updateDTO) {
errorCodeService.updateErrorCode(updateDTO);
return success(Boolean.TRUE);
}
/**
* 删除错误码
*
* @param errorCodeId 错误码编号
*/
@ApiOperation("删除错误码")
@DeleteMapping("delete")
public CommonResult<Boolean> deleteErrorCode(Integer errorCodeId) {
errorCodeService.deleteErrorCode(errorCodeId);
return success(Boolean.TRUE);
}
/**
* 获得错误码
*
* @param errorCodeId 错误码编号
* @return 错误码
*/
@ApiOperation("获取错误码")
@GetMapping("/query")
public CommonResult<ErrorCodeVO> getErrorCode(Integer errorCodeId) {
return success(errorCodeService.getErrorCode(errorCodeId));
}
/**
* 获得错误码列表
*
* @param errorCodeIds 错误码编号列表
* @return 错误码列表
*/
@ApiOperation("获取错误码列表")
@GetMapping("/query-ids")
public CommonResult<List<ErrorCodeVO>> listErrorCodes(@RequestBody List<Integer> errorCodeIds) {
return success(errorCodeService.listErrorCodes(errorCodeIds));
}
/**
* 获得错误码分页
*
* @param pageDTO 错误码分页查询
* @return 错误码分页结果
*/
@ApiOperation("获取错误码分页列表")
@GetMapping("/page")
public CommonResult<PageResult<ErrorCodeVO>> pageErrorCode(ErrorCodePageDTO pageDTO) {
return success(errorCodeService.pageErrorCode(pageDTO));
}
}

View File

@ -1,27 +0,0 @@
package cn.iocoder.dashboard.modules.system.controller.errorcode.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@ApiModel("错误码创建 DTO")
@Data
public class ErrorCodeCreateDTO {
@ApiModelProperty(value = "错误码编码", required = true, example = "10086")
@NotNull(message = "错误码编码不能为空")
private Integer code;
@ApiModelProperty(value = "错误码错误提示", required = true, example = "艿艿长的丑")
@NotEmpty(message = "错误码错误提示不能为空")
private String message;
@ApiModelProperty(value = "错误码分组", required = true, example = "user-service")
@NotEmpty(message = "错误码分组不能为空")
private String group;
@ApiModelProperty(value = "错误码备注", example = "我就是一个备注")
private String memo;
}

View File

@ -1,24 +0,0 @@
package cn.iocoder.dashboard.modules.system.controller.errorcode.dto;
import cn.iocoder.dashboard.common.pojo.PageParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 错误码分页 DTO
*/
@ApiModel("错误码分页 DTO")
@Data
@EqualsAndHashCode(callSuper = true)
public class ErrorCodePageDTO extends PageParam {
@ApiModelProperty(value = "错误码编码", required = true)
private Integer code;
@ApiModelProperty(value = "错误码错误提示", required = true)
private String message;
@ApiModelProperty(value = "错误码分组", required = true)
private String group;
}

View File

@ -1,30 +0,0 @@
package cn.iocoder.dashboard.modules.system.controller.errorcode.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@ApiModel("错误码更新 DTO")
@Data
public class ErrorCodeUpdateDTO {
@ApiModelProperty(value = "错误码编号", required = true, example = "1")
@NotNull(message = "错误码编号不能为空")
private Integer id;
@ApiModelProperty(value = "错误码编码", required = true, example = "10086")
@NotNull(message = "错误码编码不能为空")
private Integer code;
@ApiModelProperty(value = "错误码错误提示", required = true, example = "艿艿长的丑")
@NotEmpty(message = "错误码错误提示不能为空")
private String message;
@ApiModelProperty(value = "错误码分组", required = true, example = "user-service")
@NotEmpty(message = "错误码分组不能为空")
private String group;
@ApiModelProperty(value = "错误码备注", example = "我就是一个备注")
private String memo;
}

View File

@ -1,35 +0,0 @@
package cn.iocoder.dashboard.modules.system.controller.errorcode.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* 错误码
*/
@ApiModel("错误码 VO")
@Data
public class ErrorCodeVO {
@ApiModelProperty(value = "错误码编号", required = true, example = "1")
private Integer id;
@ApiModelProperty(value = "错误码编码", required = true, example = "10086")
private Integer code;
@ApiModelProperty(value = "错误码错误提示", required = true, example = "艿艿长的丑")
private String message;
@ApiModelProperty(value = "错误码类型", required = true, notes = "见 ErrorCodeTypeEnum 枚举", example = "1")
private Integer type;
@ApiModelProperty(value = "错误码分组", required = true, example = "user-service")
private String group;
@ApiModelProperty(value = "错误码备注", example = "我就是一个备注")
private String memo;
@ApiModelProperty(value = "创建时间", required = true)
private Date createTime;
@ApiModelProperty(value = "更新时间", required = false)
private Date updateTime;
}

View File

@ -91,10 +91,4 @@ public interface SysErrorCodeConstants {
ErrorCode SMS_SEND_MOBILE_NOT_EXISTS = new ErrorCode(1002012000, "手机号不存在");
ErrorCode SMS_SEND_MOBILE_TEMPLATE_PARAM_MISS = new ErrorCode(1002012001, "模板参数({})缺失");
// ========== 错误码模块 1002009000 ==========
ErrorCode ERROR_CODE_NOT_EXISTS = new ErrorCode(1002009000, "错误码不存在");
ErrorCode ERROR_CODE_DUPLICATE = new ErrorCode(1002009001, "已经存在编码为【{}}】的错误码");
ErrorCode ERROR_CAN_NOT_UPDATE_SYSTEM_TYPE_ERROR = new ErrorCode(1002004003, "不能修改类型为系统内置的错误码");
}

View File

@ -27,7 +27,7 @@ public enum SysDictTypeEnum {
INF_JOB_STATUS("inf_job_status"), // 定时任务状态的枚举
INF_JOB_LOG_STATUS("inf_job_log_status"), // 定时任务日志状态的枚举
INF_API_ERROR_LOG_PROCESS_STATUS("inf_api_error_log_process_status"), // API 错误日志的处理状态的枚举
INF_ERROR_CODE_TYPE("inf_error_code_type"), // 错误码的类型枚举
;

View File

@ -1,12 +0,0 @@
package cn.iocoder.dashboard.modules.system.service.errorcode;
import cn.iocoder.dashboard.framework.errorcode.core.service.ErrorCodeFrameworkService;
/**
* 错误码 Service 接口
*
* @author 芋道源码
*/
public interface SysErrorCodeService extends ErrorCodeFrameworkService {
}

View File

@ -1,194 +0,0 @@
package cn.iocoder.dashboard.modules.system.service.errorcode.impl;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.dashboard.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeAutoGenerateReqDTO;
import cn.iocoder.dashboard.framework.errorcode.core.dto.ErrorCodeRespDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodeCreateDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodePageDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.dto.ErrorCodeUpdateDTO;
import cn.iocoder.dashboard.modules.system.controller.errorcode.vo.ErrorCodeVO;
import cn.iocoder.dashboard.modules.infra.convert.errorcode.SysErrorCodeConvert;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import cn.iocoder.dashboard.modules.infra.dal.mysql.errorcode.InfErrorCodeMapper;
import cn.iocoder.dashboard.modules.system.enums.errorcode.SysErrorCodeTypeEnum;
import cn.iocoder.dashboard.modules.system.service.errorcode.SysErrorCodeService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static cn.iocoder.dashboard.modules.system.enums.SysErrorCodeConstants.ERROR_CODE_DUPLICATE;
import static cn.iocoder.dashboard.modules.system.enums.SysErrorCodeConstants.ERROR_CODE_NOT_EXISTS;
import static cn.iocoder.dashboard.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.dashboard.util.collection.CollectionUtils.convertSet;
/**
* 错误码 Service 实现类
*/
@Service
@Validated
@Slf4j
public class ErrorCodeServiceImpl implements SysErrorCodeService {
@Resource
private InfErrorCodeMapper errorCodeMapper;
/**
* 创建错误码
*
* @param createDTO 创建错误码 DTO
* @return 错误码
*/
public ErrorCodeVO createErrorCode(ErrorCodeCreateDTO createDTO) {
checkDuplicateErrorCode(createDTO.getCode(), null);
// 插入到数据库
InfErrorCodeDO errorCodeDO = SysErrorCodeConvert.INSTANCE.convert(createDTO);
errorCodeMapper.insert(errorCodeDO);
// 返回
return SysErrorCodeConvert.INSTANCE.convert(errorCodeDO);
}
/**
* 更新错误码
*
* @param updateDTO 更新错误码 DTO
*/
public void updateErrorCode(ErrorCodeUpdateDTO updateDTO) {
checkDuplicateErrorCode(updateDTO.getCode(), updateDTO.getId());
// 校验更新的错误码是否存在
if (errorCodeMapper.selectById(updateDTO.getId()) == null) {
throw ServiceExceptionUtil.exception(ERROR_CODE_NOT_EXISTS);
}
// 更新到数据库
InfErrorCodeDO updateObject = SysErrorCodeConvert.INSTANCE.convert(updateDTO);
errorCodeMapper.updateById(updateObject);
}
/**
* 删除错误码
*
* @param errorCodeId 错误码编号
*/
public void deleteErrorCode(Integer errorCodeId) {
// 校验删除的错误码是否存在
if (errorCodeMapper.selectById(errorCodeId) == null) {
throw ServiceExceptionUtil.exception(ERROR_CODE_NOT_EXISTS);
}
// 标记删除
errorCodeMapper.deleteById(errorCodeId);
}
/**
* 获得错误码
*
* @param errorCodeId 错误码编号
* @return 错误码
*/
public ErrorCodeVO getErrorCode(Integer errorCodeId) {
InfErrorCodeDO errorCodeDO = errorCodeMapper.selectById(errorCodeId);
return SysErrorCodeConvert.INSTANCE.convert(errorCodeDO);
}
/**
* 获得错误码列表
*
* @param errorCodeIds 错误码编号列表
* @return 错误码列表
*/
public List<ErrorCodeVO> listErrorCodes(List<Integer> errorCodeIds) {
List<InfErrorCodeDO> errorCodeDOs = errorCodeMapper.selectBatchIds(errorCodeIds);
return SysErrorCodeConvert.INSTANCE.convertList(errorCodeDOs);
}
/**
* 获得错误码分页
*
* @param pageDTO 错误码分页查询
* @return 错误码分页结果
*/
public PageResult<ErrorCodeVO> pageErrorCode(ErrorCodePageDTO pageDTO) {
IPage<InfErrorCodeDO> errorCodeDOPage = errorCodeMapper.selectPage(pageDTO);
return SysErrorCodeConvert.INSTANCE.convertPage(errorCodeDOPage);
}
/**
* 校验错误码的唯一字段是否重复
*
* 是否存在相同编码的错误码
*
* @param code 错误码编码
* @param id 错误码编号
*/
private void checkDuplicateErrorCode(Integer code, Integer id) {
InfErrorCodeDO errorCodeDO = errorCodeMapper.selectByCode(code);
if (errorCodeDO == null) {
return;
}
// 如果 id 为空说明不用比较是否为相同 id 的错误码
if (id == null) {
throw ServiceExceptionUtil.exception(ERROR_CODE_DUPLICATE);
}
if (!errorCodeDO.getId().equals(id)) {
throw ServiceExceptionUtil.exception(ERROR_CODE_DUPLICATE);
}
}
@Override
@Transactional
public void autoGenerateErrorCodes(List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs) {
if (CollUtil.isEmpty(autoGenerateDTOs)) {
return;
}
// 获得错误码
List<InfErrorCodeDO> errorCodeDOs = errorCodeMapper.selectListByCodes(
convertSet(autoGenerateDTOs, ErrorCodeAutoGenerateReqDTO::getCode));
Map<Integer, InfErrorCodeDO> errorCodeDOMap = convertMap(errorCodeDOs, InfErrorCodeDO::getCode);
// 遍历 autoGenerateBOs 数组逐个插入或更新考虑到每次量级不大就不走批量了
autoGenerateDTOs.forEach(autoGenerateDTO -> {
InfErrorCodeDO errorCodeDO = errorCodeDOMap.get(autoGenerateDTO.getCode());
// 不存在则进行新增
if (errorCodeDO == null) {
errorCodeDO = SysErrorCodeConvert.INSTANCE.convert(autoGenerateDTO)
.setType(SysErrorCodeTypeEnum.AUTO_GENERATION.getType());
errorCodeMapper.insert(errorCodeDO);
return;
}
// 存在则进行更新更新有三个前置条件
// 条件 1. 只更新自动生成的错误码 Type ErrorCodeTypeEnum.AUTO_GENERATION
if (!SysErrorCodeTypeEnum.AUTO_GENERATION.getType().equals(errorCodeDO.getType())) {
return;
}
// 条件 2. 分组 group 必须匹配避免存在错误码冲突的情况
if (!autoGenerateDTO.getApplicationName().equals(errorCodeDO.getApplicationName())) {
log.error("[autoGenerateErrorCodes][自动创建({}/{}) 错误码失败,数据库中已经存在({}/{})]",
autoGenerateDTO.getCode(), autoGenerateDTO.getApplicationName(),
errorCodeDO.getCode(), errorCodeDO.getApplicationName());
return;
}
// 条件 3. 错误提示语存在差异
if (autoGenerateDTO.getMessage().equals(errorCodeDO.getMessage())) {
return;
}
// 最终匹配进行更新
errorCodeMapper.updateById(new InfErrorCodeDO().setId(errorCodeDO.getId()).setMessage(autoGenerateDTO.getMessage()));
});
}
@Override
public List<ErrorCodeRespDTO> getErrorCodeList(String applicationName, Date minUpdateTime) {
List<InfErrorCodeDO> errorCodeDOs = errorCodeMapper.selectListByApplicationNameAndUpdateTimeGt(
applicationName, minUpdateTime);
return SysErrorCodeConvert.INSTANCE.convertList02(errorCodeDOs);
}
}

View File

@ -53,7 +53,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service
public void delete${simpleClassName}(${primaryColumn.javaType} id) {
// 校验存在
this.validate${simpleClassName}Exists(id);
// 更新
// 删除
${classNameVar}Mapper.deleteById(id);
}

View File

@ -0,0 +1,200 @@
package cn.iocoder.dashboard.modules.infra.service.errorcode;
import cn.iocoder.dashboard.BaseDbUnitTest;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeCreateReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeExportReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodePageReqVO;
import cn.iocoder.dashboard.modules.infra.controller.errorcode.vo.InfErrorCodeUpdateReqVO;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.errorcode.InfErrorCodeDO;
import cn.iocoder.dashboard.modules.infra.dal.mysql.errorcode.InfErrorCodeMapper;
import cn.iocoder.dashboard.modules.infra.enums.config.InfConfigTypeEnum;
import cn.iocoder.dashboard.modules.infra.enums.errorcode.InfErrorCodeTypeEnum;
import cn.iocoder.dashboard.modules.infra.service.errorcode.impl.InfErrorCodeServiceImpl;
import cn.iocoder.dashboard.util.collection.ArrayUtils;
import cn.iocoder.dashboard.util.object.ObjectUtils;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
import javax.annotation.Resource;
import java.util.List;
import java.util.function.Consumer;
import static cn.hutool.core.util.RandomUtil.randomEle;
import static cn.iocoder.dashboard.modules.infra.enums.InfErrorCodeConstants.ERROR_CODE_DUPLICATE;
import static cn.iocoder.dashboard.modules.infra.enums.InfErrorCodeConstants.ERROR_CODE_NOT_EXISTS;
import static cn.iocoder.dashboard.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.dashboard.util.AssertUtils.assertServiceException;
import static cn.iocoder.dashboard.util.RandomUtils.*;
import static cn.iocoder.dashboard.util.date.DateUtils.buildTime;
import static org.junit.jupiter.api.Assertions.*;
/**
* {@link InfErrorCodeServiceImpl} 的单元测试类
*
* @author 芋道源码
*/
@Import(InfErrorCodeServiceImpl.class)
public class InfErrorCodeServiceTest extends BaseDbUnitTest {
@Resource
private InfErrorCodeServiceImpl errorCodeService;
@Resource
private InfErrorCodeMapper errorCodeMapper;
@Test
public void testCreateErrorCode_success() {
// 准备参数
InfErrorCodeCreateReqVO reqVO = randomPojo(InfErrorCodeCreateReqVO.class);
// 调用
Long errorCodeId = errorCodeService.createErrorCode(reqVO);
// 断言
assertNotNull(errorCodeId);
// 校验记录的属性是否正确
InfErrorCodeDO errorCode = errorCodeMapper.selectById(errorCodeId);
assertPojoEquals(reqVO, errorCode);
assertEquals(InfErrorCodeTypeEnum.MANUAL_OPERATION.getType(), errorCode.getType());
}
@Test
public void testUpdateErrorCode_success() {
// mock 数据
InfErrorCodeDO dbErrorCode = randomInfErrorCodeDO();
errorCodeMapper.insert(dbErrorCode);// @Sql: 先插入出一条存在的数据
// 准备参数
InfErrorCodeUpdateReqVO reqVO = randomPojo(InfErrorCodeUpdateReqVO.class, o -> {
o.setId(dbErrorCode.getId()); // 设置更新的 ID
});
// 调用
errorCodeService.updateErrorCode(reqVO);
// 校验是否更新正确
InfErrorCodeDO errorCode = errorCodeMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, errorCode);
assertEquals(InfErrorCodeTypeEnum.MANUAL_OPERATION.getType(), errorCode.getType());
}
@Test
public void testDeleteErrorCode_success() {
// mock 数据
InfErrorCodeDO dbErrorCode = randomInfErrorCodeDO();
errorCodeMapper.insert(dbErrorCode);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbErrorCode.getId();
// 调用
errorCodeService.deleteErrorCode(id);
// 校验数据不存在了
assertNull(errorCodeMapper.selectById(id));
}
@Test
public void testGetErrorCodePage() {
// mock 数据
InfErrorCodeDO dbErrorCode = initGetErrorCodePage();
// 准备参数
InfErrorCodePageReqVO reqVO = new InfErrorCodePageReqVO();
reqVO.setType(InfErrorCodeTypeEnum.AUTO_GENERATION.getType());
reqVO.setApplicationName("yudao");
reqVO.setCode(1);
reqVO.setMessage("yu");
reqVO.setBeginCreateTime(buildTime(2020, 11, 1));
reqVO.setEndCreateTime(buildTime(2020, 11, 30));
// 调用
PageResult<InfErrorCodeDO> pageResult = errorCodeService.getErrorCodePage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbErrorCode, pageResult.getList().get(0));
}
/**
* 初始化 getErrorCodePage 方法的测试数据
*/
private InfErrorCodeDO initGetErrorCodePage() {
InfErrorCodeDO dbErrorCode = randomInfErrorCodeDO(o -> { // 等会查询到
o.setType(InfErrorCodeTypeEnum.AUTO_GENERATION.getType());
o.setApplicationName("yudaoyuanma");
o.setCode(1);
o.setMessage("yudao");
o.setCreateTime(buildTime(2020, 11, 11));
});
errorCodeMapper.insert(dbErrorCode);
// 测试 type 不匹配
errorCodeMapper.insert(ObjectUtils.clone(dbErrorCode, o -> o.setType(InfErrorCodeTypeEnum.MANUAL_OPERATION.getType())));
// 测试 applicationName 不匹配
errorCodeMapper.insert(ObjectUtils.clone(dbErrorCode, o -> o.setApplicationName("yunai")));
// 测试 code 不匹配
errorCodeMapper.insert(ObjectUtils.clone(dbErrorCode, o -> o.setCode(2)));
// 测试 message 不匹配
errorCodeMapper.insert(ObjectUtils.clone(dbErrorCode, o -> o.setMessage("nai")));
// 测试 createTime 不匹配
errorCodeMapper.insert(ObjectUtils.clone(dbErrorCode, o -> o.setCreateTime(buildTime(2020, 12, 12))));
return dbErrorCode;
}
@Test
public void testGetErrorCodeList() {
// mock 数据
InfErrorCodeDO dbErrorCode = initGetErrorCodePage();
// 准备参数
InfErrorCodeExportReqVO reqVO = new InfErrorCodeExportReqVO();
reqVO.setType(InfErrorCodeTypeEnum.AUTO_GENERATION.getType());
reqVO.setApplicationName("yudao");
reqVO.setCode(1);
reqVO.setMessage("yu");
reqVO.setBeginCreateTime(buildTime(2020, 11, 1));
reqVO.setEndCreateTime(buildTime(2020, 11, 30));
// 调用
List<InfErrorCodeDO> list = errorCodeService.getErrorCodeList(reqVO);
// 断言
assertEquals(1, list.size());
assertPojoEquals(dbErrorCode, list.get(0));
}
@Test
public void testValidateCodeDuplicate_codeDuplicateForCreate() {
// 准备参数
Integer code = randomInteger();
// mock 数据
errorCodeMapper.insert(randomInfErrorCodeDO(o -> o.setCode(code)));
// 调用校验异常
assertServiceException(() -> errorCodeService.validateCodeDuplicate(code, null),
ERROR_CODE_DUPLICATE);
}
@Test
public void testValidateCodeDuplicate_codeDuplicateForUpdate() {
// 准备参数
Long id = randomLongId();
Integer code = randomInteger();
// mock 数据
errorCodeMapper.insert(randomInfErrorCodeDO(o -> o.setCode(code)));
// 调用校验异常
assertServiceException(() -> errorCodeService.validateCodeDuplicate(code, id),
ERROR_CODE_DUPLICATE);
}
@Test
public void testValidateErrorCodeExists_notExists() {
assertServiceException(() -> errorCodeService.validateErrorCodeExists(null),
ERROR_CODE_NOT_EXISTS);
}
// ========== 随机对象 ==========
@SafeVarargs
private static InfErrorCodeDO randomInfErrorCodeDO(Consumer<InfErrorCodeDO>... consumers) {
Consumer<InfErrorCodeDO> consumer = (o) -> {
o.setType(randomEle(InfConfigTypeEnum.values()).getType()); // 保证 key 的范围
};
return randomPojo(InfErrorCodeDO.class, ArrayUtils.append(consumer, consumers));
}
}

View File

@ -5,6 +5,7 @@ DELETE FROM "inf_job";
DELETE FROM "inf_job_log";
DELETE FROM "inf_api_access_log";
DELETE FROM "inf_api_error_log";
DELETE FROM "inf_error_code";
-- sys 开头的 DB
DELETE FROM "sys_dept";

View File

@ -359,7 +359,7 @@ CREATE TABLE IF NOT EXISTS "sys_sms_channel" (
PRIMARY KEY ("id")
) COMMENT '短信渠道';
CREATE TABLE "sys_sms_template" (
CREATE TABLE IF NOT EXISTS "sys_sms_template" (
"id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"type" tinyint NOT NULL,
"status" tinyint NOT NULL,
@ -379,7 +379,7 @@ CREATE TABLE "sys_sms_template" (
PRIMARY KEY ("id")
) COMMENT '短信模板';
CREATE TABLE "sys_sms_log" (
CREATE TABLE IF NOT EXISTS "sys_sms_log" (
"id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"channel_id" bigint NOT NULL,
"channel_code" varchar(63) NOT NULL,
@ -411,3 +411,18 @@ CREATE TABLE "sys_sms_log" (
"deleted" bit NOT NULL DEFAULT FALSE,
PRIMARY KEY ("id")
) COMMENT '短信日志';
CREATE TABLE IF NOT EXISTS "inf_error_code" (
"id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY,
"type" tinyint NOT NULL DEFAULT '0',
"application_name" varchar(50) NOT NULL,
"code" int NOT NULL DEFAULT '0',
"message" varchar(512) NOT NULL DEFAULT '',
"memo" varchar(512) DEFAULT '',
"creator" varchar(64) DEFAULT '',
"create_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updater" varchar(64) DEFAULT '',
"update_time" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted" bit NOT NULL DEFAULT FALSE,
PRIMARY KEY ("id")
) COMMENT '错误码表';