sys_dict_data.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * @desc:字典数据
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu<yxh669@qq.com>
  5. * @Date: 2022/3/18 11:55
  6. */
  7. package service
  8. import (
  9. "context"
  10. "github.com/gogf/gf/v2/frame/g"
  11. "github.com/gogf/gf/v2/text/gstr"
  12. "github.com/gogf/gf/v2/util/gconv"
  13. "github.com/tiger1103/gfast/v3/api/v1/system"
  14. commonConsts "github.com/tiger1103/gfast/v3/internal/app/common/consts"
  15. commonModel "github.com/tiger1103/gfast/v3/internal/app/common/model"
  16. commonDao "github.com/tiger1103/gfast/v3/internal/app/common/service/internal/dao"
  17. "github.com/tiger1103/gfast/v3/library/liberr"
  18. )
  19. type IDictData interface {
  20. GetDictWithDataByType(ctx context.Context, req *system.GetDictReq) (dict *system.GetDictRes, err error)
  21. }
  22. type dictDataImpl struct {
  23. }
  24. var dictData = dictDataImpl{}
  25. func DictData() IDictData {
  26. return IDictData(&dictData)
  27. }
  28. // GetDictWithDataByType 通过字典键类型获取选项
  29. func (s dictDataImpl) GetDictWithDataByType(ctx context.Context, req *system.GetDictReq) (dict *system.GetDictRes,
  30. err error) {
  31. cache := Cache()
  32. cacheKey := commonConsts.CacheSysDict + "_" + req.DictType
  33. //从缓存获取
  34. iDict := cache.GetOrSetFuncLock(ctx, cacheKey, func(ctx context.Context) (value interface{}, err error) {
  35. err = g.Try(func() {
  36. //从数据库获取
  37. dict = &system.GetDictRes{}
  38. //获取类型数据
  39. err = commonDao.SysDictType.Ctx(ctx).Where(commonDao.SysDictType.Columns().DictType, req.DictType).
  40. Where(commonDao.SysDictType.Columns().Status, 1).Fields(commonModel.DictTypeRes{}).Scan(&dict.Info)
  41. liberr.ErrIsNil(ctx, err, "获取字典类型失败")
  42. err = commonDao.SysDictData.Ctx(ctx).Fields(commonModel.DictDataRes{}).
  43. Where(commonDao.SysDictData.Columns().DictType, req.DictType).
  44. Order(commonDao.SysDictData.Columns().DictSort + " asc," +
  45. commonDao.SysDictData.Columns().DictCode + " asc").
  46. Scan(&dict.Values)
  47. liberr.ErrIsNil(ctx, err, "获取字典数据失败")
  48. })
  49. value = dict
  50. return
  51. }, 0, commonConsts.CacheSysDictTag)
  52. if iDict != nil {
  53. err = gconv.Struct(iDict, &dict)
  54. if err != nil {
  55. return
  56. }
  57. }
  58. //设置给定的默认值
  59. for _, v := range dict.Values {
  60. if req.DefaultValue != "" {
  61. if gstr.Equal(req.DefaultValue, v.DictValue) {
  62. v.IsDefault = 1
  63. } else {
  64. v.IsDefault = 0
  65. }
  66. }
  67. }
  68. return
  69. }