优化sysconfig 业务

This commit is contained in:
zhangwenjian
2020-10-14 11:42:01 +08:00
parent d1d545b29c
commit 21603d5a4c
10 changed files with 262 additions and 307 deletions
+43
View File
@@ -0,0 +1,43 @@
package sys_config
import (
"github.com/gin-gonic/gin"
"go-admin/app/admin/service"
"go-admin/app/admin/service/dto"
"go-admin/common/apis"
"go-admin/common/log"
"go-admin/tools"
"go-admin/tools/app"
)
type SysConfig struct {
apis.Api
}
// GetSysConfigByKEYForService 根据Key获取SysConfig的Service
func (e *SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
msgID := tools.GenerateMsgIDFromContext(c)
db, err := e.GetOrm(c)
if err != nil {
log.Errorf("msgID[%s] error:%s", msgID, err)
app.Error(c, 500, err, "")
return
}
var v dto.SysConfigControl
err = c.Bind(&v)
if err != nil {
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
app.Error(c, 422, err, "参数验证失败")
return
}
s := service.SysConfig{}
s.MsgID = msgID
s.Orm = db
err = s.GetSysConfigByKEY(&v)
if err != nil {
app.Error(c, 500, err, "")
return
}
app.OK(c, v, s.Msg)
}
-149
View File
@@ -1,149 +0,0 @@
package system
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"go-admin/app/admin/models"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/app/msg"
)
// @Summary 配置列表数据
// @Description 获取JSON
// @Tags 配置
// @Param configKey query string false "configKey"
// @Param configName query string false "configName"
// @Param configType query string false "configType"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/configList [get]
// @Security Bearer
func GetConfigList(c *gin.Context) {
var data models.SysConfig
var err error
var pageSize = 10
var pageIndex = 1
if size := c.Request.FormValue("pageSize"); size != "" {
pageSize, err = tools.StringToInt(size)
}
if index := c.Request.FormValue("pageIndex"); index != "" {
pageIndex, err = tools.StringToInt(index)
}
data.ConfigKey = c.Request.FormValue("configKey")
data.ConfigName = c.Request.FormValue("configName")
data.ConfigType = c.Request.FormValue("configType")
data.DataScope = tools.GetUserIdStr(c)
result, count, err := data.GetPage(pageSize, pageIndex)
tools.HasError(err, "", -1)
var mp = make(map[string]interface{}, 3)
mp["list"] = result
mp["count"] = count
mp["pageIndex"] = pageIndex
mp["pageSize"] = pageSize
var res app.Response
res.Data = mp
c.JSON(http.StatusOK, res.ReturnOK())
}
// @Summary 获取配置
// @Description 获取JSON
// @Tags 配置
// @Param configId path int true "配置编码"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/config/{configId} [get]
// @Security Bearer
func GetConfig(c *gin.Context) {
var Config models.SysConfig
Config.ConfigId, _ = tools.StringToInt(c.Param("configId"))
result, err := Config.Get()
tools.HasError(err, "抱歉未找到相关信息", -1)
var res app.Response
res.Data = result
c.JSON(http.StatusOK, res.ReturnOK())
}
// @Summary 获取配置
// @Description 获取JSON
// @Tags 配置
// @Param configKey path int true "configKey"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/configKey/{configKey} [get]
// @Security Bearer
func GetConfigByConfigKey(c *gin.Context) {
var Config models.SysConfig
Config.ConfigKey = c.Param("configKey")
result, err := Config.Get()
tools.HasError(err, "抱歉未找到相关信息", -1)
app.OK(c, result, result.ConfigValue)
}
// @Summary 添加配置
// @Description 获取JSON
// @Tags 配置
// @Accept application/json
// @Product application/json
// @Param data body models.SysConfig true "data"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/dict/data [post]
// @Security Bearer
func InsertConfig(c *gin.Context) {
var data models.SysConfig
err := c.BindWith(&data, binding.JSON)
data.CreateBy = tools.GetUserIdStr(c)
tools.HasError(err, "", 500)
result, err := data.Create()
tools.HasError(err, "", -1)
app.OK(c, result, "")
}
// @Summary 修改配置
// @Description 获取JSON
// @Tags 配置
// @Accept application/json
// @Product application/json
// @Param data body models.SysConfig true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/config [put]
// @Security Bearer
func UpdateConfig(c *gin.Context) {
var data models.SysConfig
err := c.BindWith(&data, binding.JSON)
tools.HasError(err, "数据解析失败", -1)
data.UpdateBy = tools.GetUserIdStr(c)
result, err := data.Update(data.ConfigId)
tools.HasError(err, "", -1)
app.OK(c, result, "")
}
// @Summary 删除配置
// @Description 删除数据
// @Tags 配置
// @Param configId path int true "configId"
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
// @Router /api/v1/config/{configId} [delete]
func DeleteConfig(c *gin.Context) {
var data models.SysConfig
data.UpdateBy = tools.GetUserIdStr(c)
IDS := tools.IdsStrToIdsIntGroup("configId", c)
result, err := data.BatchDelete(IDS)
tools.HasError(err, "修改失败", 500)
app.OK(c, result, msg.DeletedSuccess)
}
-134
View File
@@ -1,134 +0,0 @@
package models
import (
"errors"
_ "time"
orm "go-admin/common/global"
"go-admin/tools"
)
type SysConfig struct {
ConfigId int `json:"configId" gorm:"primary_key;auto_increment;"` //编码
ConfigName string `json:"configName" gorm:"size:128;"` //参数名称
ConfigKey string `json:"configKey" gorm:"size:128;"` //参数键名
ConfigValue string `json:"configValue" gorm:"size:255;"` //参数键值
ConfigType string `json:"configType" gorm:"size:64;"` //是否系统内置
Remark string `json:"remark" gorm:"size:128;"` //备注
CreateBy string `json:"createBy" gorm:"size:128;"`
UpdateBy string `json:"updateBy" gorm:"size:128;"`
BaseModel
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
}
func (SysConfig) TableName() string {
return "sys_config"
}
// Config 创建
func (e *SysConfig) Create() (SysConfig, error) {
var doc SysConfig
var i int64
orm.Eloquent.Table(e.TableName()).Where("config_name=? or config_key = ?", e.ConfigName, e.ConfigKey).Count(&i)
if i > 0 {
return doc, errors.New("参数名称或者参数键名已经存在!")
}
result := orm.Eloquent.Table(e.TableName()).Create(&e)
if result.Error != nil {
err := result.Error
return doc, err
}
doc = *e
return doc, nil
}
// 获取 Config
func (e *SysConfig) Get() (SysConfig, error) {
var doc SysConfig
table := orm.Eloquent.Table(e.TableName())
if e.ConfigId != 0 {
table = table.Where("config_id = ?", e.ConfigId)
}
if e.ConfigKey != "" {
table = table.Where("config_key = ?", e.ConfigKey)
}
if err := table.First(&doc).Error; err != nil {
return doc, err
}
return doc, nil
}
func (e *SysConfig) GetPage(pageSize int, pageIndex int) ([]SysConfig, int, error) {
var doc []SysConfig
table := orm.Eloquent.Table(e.TableName())
if e.ConfigName != "" {
table = table.Where("config_name = ?", e.ConfigName)
}
if e.ConfigKey != "" {
table = table.Where("config_key = ?", e.ConfigKey)
}
if e.ConfigType != "" {
table = table.Where("config_type = ?", e.ConfigType)
}
// 数据权限控制
dataPermission := new(DataPermission)
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
table, err := dataPermission.GetDataScope("sys_config", table)
if err != nil {
return nil, 0, err
}
var count int64
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
return nil, 0, err
}
//table.Where("`deleted_at` IS NULL").Count(&count)
return doc, int(count), nil
}
func (e *SysConfig) Update(id int) (update SysConfig, err error) {
if err = orm.Eloquent.Table(e.TableName()).Where("config_id = ?", id).First(&update).Error; err != nil {
return
}
if e.ConfigName != "" && e.ConfigName != update.ConfigName {
return update, errors.New("参数名称不允许修改!")
}
if e.ConfigKey != "" && e.ConfigKey != update.ConfigKey {
return update, errors.New("参数键名不允许修改!")
}
//参数1:是要修改的数据
//参数2:是修改的数据
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
return
}
return
}
func (e *SysConfig) Delete() (success bool, err error) {
if err = orm.Eloquent.Table(e.TableName()).Where("config_id = ?", e.ConfigId).Delete(&SysConfig{}).Error; err != nil {
success = false
return
}
success = true
return
}
func (e *SysConfig) BatchDelete(id []int) (Result bool, err error) {
if err = orm.Eloquent.Table(e.TableName()).Where("config_id in (?)", id).Delete(&SysConfig{}).Error; err != nil {
return
}
Result = true
return
}
+30
View File
@@ -0,0 +1,30 @@
package models
import (
"gorm.io/gorm"
"go-admin/common/models"
)
type SysConfig struct {
gorm.Model
models.ControlBy
ConfigName string `json:"configName" gorm:"type:varchar(128);comment:ConfigName"` //
ConfigKey string `json:"configKey" gorm:"type:varchar(128);comment:ConfigKey"` //
ConfigValue string `json:"configValue" gorm:"type:varchar(255);comment:ConfigValue"` //
ConfigType string `json:"configType" gorm:"type:varchar(64);comment:ConfigType"` //
Remark string `json:"remark" gorm:"type:varchar(128);comment:Remark"` //
}
func (SysConfig) TableName() string {
return "sys_config"
}
func (e *SysConfig) Generate() models.ActiveRecord {
o := *e
return &o
}
func (e *SysConfig) GetId() interface{} {
return e.ID
}
+37
View File
@@ -0,0 +1,37 @@
package router
import (
"github.com/gin-gonic/gin"
"go-admin/app/admin/apis/sys_config"
"go-admin/app/admin/middleware"
"go-admin/app/admin/models"
"go-admin/app/admin/service/dto"
"go-admin/common/actions"
jwt "go-admin/pkg/jwtauth"
)
func init() {
routerCheckRole = append(routerCheckRole, registerSysConfigRouter)
}
// 需认证的路由代码
func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
model := &models.SysConfig{}
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysConfigSearch), func() interface{} {
list := make([]models.SysConfig, 0)
return &list
}))
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysConfigById), nil))
r.POST("", actions.CreateAction(new(dto.SysConfigControl)))
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysConfigControl)))
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysConfigById)))
}
r1 := v1.Group("/configKey").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
model := &sys_config.SysConfig{}
r1.POST("", model.GetSysConfigByKEYForService)
}
}
+1 -20
View File
@@ -67,13 +67,9 @@ func sysNoCheckRoleRouter(r *gin.RouterGroup) {
v1.GET("/dict/databytype/:dictType", dict.GetDictDataByDictType)
registerDBRouter(v1)
registerSysTableRouter(v1)
registerPublicRouter(v1)
registerSysSettingRouter(v1)
}
func registerDBRouter(api *gin.RouterGroup) {
@@ -103,11 +99,8 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
r.POST("/login", authMiddleware.LoginHandler)
// Refresh time can be longer than token timeout
r.GET("/refresh_token", authMiddleware.RefreshHandler)
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/ws/:id/:channel", ws.WebsocketManager.WsClient)
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/wslogout/:id/:channel", ws.WebsocketManager.UnWsClient)
v1 := r.Group("/api/v1")
registerPageRouter(v1, authMiddleware)
@@ -116,7 +109,6 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
registerDictRouter(v1, authMiddleware)
registerSysUserRouter(v1, authMiddleware)
registerRoleRouter(v1, authMiddleware)
registerConfigRouter(v1, authMiddleware)
registerUserCenterRouter(v1, authMiddleware)
registerPostRouter(v1, authMiddleware)
registerMenuRouter(v1, authMiddleware)
@@ -137,7 +129,6 @@ func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
v1auth.GET("/menuids", system.GetMenuIDS)
v1auth.GET("/operloglist", log2.GetOperLogList)
v1auth.GET("/configKey/:configKey", system.GetConfigByConfigKey)
}
}
@@ -148,7 +139,7 @@ func registerPageRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
v1auth.GET("/deptTree", system.GetDeptTree)
v1auth.GET("/sysUserList", system.GetSysUserList)
v1auth.GET("/rolelist", system.GetRoleList)
v1auth.GET("/configList", system.GetConfigList)
//v1auth.GET("/configList", system.GetConfigList)
v1auth.GET("/postlist", system.GetPostList)
v1auth.GET("/menulist", system.GetMenuList)
v1auth.GET("/loginloglist", log2.GetLoginLogList)
@@ -202,16 +193,6 @@ func registerMenuRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
}
}
func registerConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
config := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
config.GET("/:configId", system.GetConfig)
config.POST("", system.InsertConfig)
config.PUT("", system.UpdateConfig)
config.DELETE("/:configId", system.DeleteConfig)
}
}
func registerRoleRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
role := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
+93
View File
@@ -0,0 +1,93 @@
package dto
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go-admin/app/admin/models"
"go-admin/common/dto"
"go-admin/common/log"
common "go-admin/common/models"
"go-admin/tools"
)
type SysConfigSearch struct {
dto.Pagination `search:"-"`
ConfigName string `form:"configName" search:"type:exact;column:config_name;table:sys_config" comment:""`
ConfigKey string `form:"configKey" search:"type:exact;column:config_key;table:sys_config" comment:""`
ConfigType string `form:"configType" search:"type:exact;column:config_type;table:sys_config" comment:""`
}
func (m *SysConfigSearch) GetNeedSearch() interface{} {
return *m
}
func (m *SysConfigSearch) Bind(ctx *gin.Context) error {
msgID := tools.GenerateMsgIDFromContext(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
}
return err
}
func (m *SysConfigSearch) Generate() dto.Index {
o := *m
return &o
}
type SysConfigControl struct {
ID uint `uri:"ID" comment:"编码"` // 编码
ConfigName string `json:"configName" comment:""`
ConfigKey string `json:"configKey" comment:""`
ConfigValue string `json:"configValue" comment:""`
ConfigType string `json:"configType" comment:""`
Remark string `json:"remark" comment:""`
}
func (s *SysConfigControl) Bind(ctx *gin.Context) error {
msgID := tools.GenerateMsgIDFromContext(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
return err
}
err = ctx.ShouldBind(s)
if err != nil {
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
}
return err
}
func (s *SysConfigControl) Generate() dto.Control {
cp := *s
return &cp
}
func (s *SysConfigControl) GenerateM() (common.ActiveRecord, error) {
return &models.SysConfig{
Model: gorm.Model{ID: s.ID},
ConfigName: s.ConfigName,
ConfigKey: s.ConfigKey,
ConfigValue: s.ConfigValue,
ConfigType: s.ConfigType,
Remark: s.Remark,
}, nil
}
func (s *SysConfigControl) GetId() interface{} {
return s.ID
}
type SysConfigById struct {
dto.ObjectById
}
func (s *SysConfigById) Generate() dto.Control {
cp := *s
return &cp
}
func (s *SysConfigById) GenerateM() (common.ActiveRecord, error) {
return &models.SysConfig{}, nil
}
+27
View File
@@ -0,0 +1,27 @@
package service
import (
"go-admin/app/admin/models"
"go-admin/app/admin/service/dto"
"go-admin/common/log"
"go-admin/common/service"
)
type SysConfig struct {
service.Service
}
// GetSysConfigByKEY 根据Key获取SysConfig
func (e *SysConfig) GetSysConfigByKEY(c *dto.SysConfigControl) error {
var err error
var data models.SysConfig
msgID := e.MsgID
data.ConfigKey = c.ConfigKey
err = e.Orm.Table(data.TableName()).Where("config_key = ?", data.ConfigKey).First(c).Error
if err != nil {
log.Errorf("msgID[%s] db error:%s", msgID, err)
return err
}
return nil
}