Merge pull request #222 from matchstalk/table/dev

使用action代替api单个操作
This commit is contained in:
wenjianzhang
2020-08-30 00:23:36 +08:00
committed by GitHub
18 changed files with 409 additions and 7 deletions
+39
View File
@@ -0,0 +1,39 @@
package actions
import (
"errors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/model"
)
// CreateAction 通用新增动作
func CreateAction(m model.ActiveRecord) gin.HandlerFunc {
return func(c *gin.Context) {
object := m.Generate()
var err error
idb, exist := c.Get("db")
if !exist {
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
switch idb.(type) {
case *gorm.DB:
//新增操作
db := idb.(*gorm.DB)
err = c.Bind(object)
tools.HasError(err, "参数验证失败", 422)
err = db.WithContext(c).Create(object).Error
tools.HasError(err, "创建失败", 500)
default:
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
app.OK(c, object.GetId(), "创建成功")
c.Next()
}
}
+42
View File
@@ -0,0 +1,42 @@
package actions
import (
"errors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/model"
)
// DeleteAction 通用删除动作
func DeleteAction(m model.ActiveRecord) gin.HandlerFunc {
return func(c *gin.Context) {
object := m.Generate()
var err error
idb, exist := c.Get("db")
if !exist {
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
switch idb.(type) {
case *gorm.DB:
//新增操作
db := idb.(*gorm.DB)
var generalDelDto tools.GeneralDelDto
err = c.Bind(&generalDelDto)
tools.HasError(err, "参数验证失败", 422)
err = c.BindUri(&generalDelDto)
tools.HasError(err, "参数验证失败", 422)
err = db.WithContext(c).Where(generalDelDto.GetIds()).Delete(object).Error
tools.HasError(err, "更新失败", 500)
default:
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
app.OK(c, object.GetId(), "更新成功")
c.Next()
}
}
+56
View File
@@ -0,0 +1,56 @@
package actions
import (
"errors"
"go-admin/dto"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/model"
)
// IndexAction 通用查询动作
func IndexAction(m model.ActiveRecord, d dto.Dtor) gin.HandlerFunc {
return func(c *gin.Context) {
object := m.Generate()
req := d.Generate()
var err error
idb, exist := c.Get("db")
if !exist {
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
list := object.GenerateList()
var count int64
switch idb.(type) {
case *gorm.DB:
//新增操作
db := idb.(*gorm.DB)
err = c.Bind(req)
tools.HasError(err, "参数验证失败", 422)
err = req.Validate()
tools.HasError(err, "参数验证失败", 422)
p, err := newDataPermission(db, tools.GetUserId(c))
tools.HasError(err, "权限范围鉴定错误", 500)
err = db.WithContext(c).Model(object).
Scopes(
tools.MakeCondition(req.GetNeedSearch()),
tools.Paginate(req.GetPageSize(), req.GetPageIndex()),
Permission(object.TableName(), p),
).
Find(list).Limit(-1).Offset(-1).
Count(&count).Error
if !errors.Is(err, gorm.ErrRecordNotFound) {
tools.HasError(err, "查询失败", 500)
}
default:
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
app.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
c.Next()
}
}
+61
View File
@@ -0,0 +1,61 @@
package actions
import (
"errors"
"go-admin/models"
"go-admin/tools/config"
"gorm.io/gorm"
"go-admin/tools"
)
type dataPermission struct {
DataScope string
UserId int
DeptId int
RoleId int
}
func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error) {
var err error
p := &dataPermission{}
sysUser := new(models.SysUser)
sysRole := new(models.SysRole)
err = sysUser.GetByUserId(tx, userId)
if err != nil {
err = errors.New("获取用户数据出错 msg:" + err.Error())
return nil, err
}
p.UserId = sysUser.UserId
p.RoleId = sysUser.RoleId
p.DeptId = sysUser.DeptId
err = sysRole.GetById(tx, sysUser.RoleId)
if err != nil {
err = errors.New("获取用户数据出错 msg:" + err.Error())
return nil, err
}
p.DataScope = sysRole.DataScope
return p, nil
}
func Permission(tableName string, p *dataPermission) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if !config.ApplicationConfig.EnableDP {
return db
}
switch p.DataScope {
case "2":
return db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", p.RoleId)
case "3":
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", p.DeptId)
case "4":
return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+tools.IntToString(p.DeptId)+"%")
case "5":
return db.Where(tableName+".create_by = ?", p.UserId)
default:
return db
}
}
}
+39
View File
@@ -0,0 +1,39 @@
package actions
import (
"errors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/model"
)
// UpdateAction 通用更新动作
func UpdateAction(m model.ActiveRecord) gin.HandlerFunc {
return func(c *gin.Context) {
object := m.Generate()
var err error
idb, exist := c.Get("db")
if !exist {
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
switch idb.(type) {
case *gorm.DB:
//新增操作
db := idb.(*gorm.DB)
err = c.Bind(object)
tools.HasError(err, "参数验证失败", 422)
err = db.WithContext(c).Updates(object).Error
tools.HasError(err, "更新失败", 500)
default:
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
app.OK(c, object.GetId(), "更新成功")
c.Next()
}
}
+40
View File
@@ -0,0 +1,40 @@
package actions
import (
"errors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go-admin/tools"
"go-admin/tools/app"
"go-admin/tools/model"
)
// ViewAction 通用详情动作
func ViewAction(m model.ActiveRecord) gin.HandlerFunc {
return func(c *gin.Context) {
object := m.Generate()
var err error
idb, exist := c.Get("db")
if !exist {
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
switch idb.(type) {
case *gorm.DB:
//新增操作
db := idb.(*gorm.DB)
var generalGetDto tools.GeneralGetDto
err = c.BindUri(&generalGetDto)
tools.HasError(err, "参数验证失败", 422)
err = db.WithContext(c).Where(generalGetDto.Id).First(object).Error
tools.HasError(err, "查看失败", 500)
default:
err = errors.New("db connect not exist")
tools.HasError(err, "", 500)
}
app.OK(c, object, "查看成功")
c.Next()
}
}
+6
View File
@@ -0,0 +1,6 @@
package dto
type Pagination struct {
PageIndex int `form:"pageIndex"`
PageSize int `form:"pageSize"`
}
+22
View File
@@ -1,6 +1,7 @@
package dto
type SysJobSearch struct {
Pagination `search:"-"`
JobId int `form:"jobId" search:"type:exact;column:job_id;table:sys_job"`
JobName string `form:"jobName" search:"type:icontains;column:job_name;table:sys_job"`
JobGroup string `form:"jobGroup" search:"type:exact;column:job_group;table:sys_job"`
@@ -8,3 +9,24 @@ type SysJobSearch struct {
InvokeTarget string `form:"invokeTarget" search:"type:exact;column:invoke_target;table:sys_job"`
Status int `form:"status" search:"type:exact;column:status;table:sys_job"`
}
func (m *SysJobSearch) GetNeedSearch() interface{} {
return *m
}
func (m *SysJobSearch) Validate() error {
return nil
}
func (m *SysJobSearch) Generate() Dtor {
o := *m
return &o
}
func (m *SysJobSearch) GetPageIndex() int {
return m.PageIndex
}
func (m *SysJobSearch) GetPageSize() int {
return m.PageSize
}
+9
View File
@@ -0,0 +1,9 @@
package dto
type Dtor interface {
Validate() error
Generate() Dtor
GetPageIndex() int
GetPageSize() int
GetNeedSearch() interface{}
}
+1
View File
@@ -30,6 +30,7 @@ require (
github.com/unrolled/secure v1.0.8
go.uber.org/multierr v1.5.0 // indirect
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a
gopkg.in/ffmt.v1 v1.5.6
gorm.io/driver/mysql v0.3.2
gorm.io/driver/postgres v0.2.9
gorm.io/driver/sqlite v1.0.9
+17
View File
@@ -0,0 +1,17 @@
package middleware
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
func WithContextDb(dbMap map[string]*gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
if db, ok := dbMap["*"]; ok {
c.Set("db", db)
} else {
c.Set("db", dbMap[c.Request.Host])
}
c.Next()
}
}
+5
View File
@@ -2,6 +2,7 @@ package models
import (
"github.com/pkg/errors"
"gorm.io/gorm"
orm "go-admin/global"
"go-admin/tools"
@@ -33,6 +34,10 @@ type MenuIdList struct {
MenuId int `json:"menuId"`
}
func (role *SysRole) GetById(tx *gorm.DB, id interface{}) error {
return tx.First(role, id).Error
}
func (role *SysRole) GetPage(pageSize int, pageIndex int) ([]SysRole, int, error) {
var doc []SysRole
+15
View File
@@ -3,6 +3,7 @@ package models
import (
orm "go-admin/global"
"go-admin/tools"
"go-admin/tools/model"
)
type SysJob struct {
@@ -27,6 +28,20 @@ func (SysJob) TableName() string {
return "sys_job"
}
func (e *SysJob) Generate() model.ActiveRecord {
o := *e
return &o
}
func (e *SysJob) GenerateList() interface{} {
list := make([]SysJob, 0)
return &list
}
func (e *SysJob) GetId() interface{} {
return e.JobId
}
// 创建SysJob
func (e *SysJob) Create() (err error) {
return orm.Eloquent.Table(e.TableName()).Create(e).Error
+6 -1
View File
@@ -2,6 +2,7 @@ package models
import (
"errors"
"gorm.io/gorm"
"log"
"strings"
@@ -224,7 +225,7 @@ func (e *SysUser) GetPage(pageSize int, pageIndex int) ([]SysUserPage, int, erro
var count int64
if err := table.Scopes(DataScopes(e.TableName(),userid)).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
if err := table.Scopes(DataScopes(e.TableName(), userid)).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
return nil, 0, err
}
//table.Where("sys_user.deleted_at IS NULL").Count(&count)
@@ -316,3 +317,7 @@ func (e *SysUser) SetPwd(pwd SysUserPwd) (Result bool, err error) {
tools.HasError(err, "更新密码失败(代码202)", 500)
return
}
func (e *SysUser) GetByUserId(tx *gorm.DB, id interface{}) error {
return tx.First(e, id).Error
}
+2
View File
@@ -8,6 +8,7 @@ import (
_ "go-admin/pkg/jwtauth"
"go-admin/tools"
config2 "go-admin/tools/config"
"gorm.io/gorm"
)
func InitRouter() *gin.Engine {
@@ -20,6 +21,7 @@ func InitRouter() *gin.Engine {
if config2.SslConfig.Enable {
r.Use(handler.TlsHandler())
}
r.Use(middleware.WithContextDb(map[string]*gorm.DB{"*": global.Eloquent}))
middleware.InitMiddleware(r)
// the jwt middleware
authMiddleware, err := middleware.AuthInit()
+15 -5
View File
@@ -1,6 +1,7 @@
package router
import (
"go-admin/apis/actions"
log2 "go-admin/apis/log"
"go-admin/apis/monitor"
"go-admin/apis/public"
@@ -9,8 +10,10 @@ import (
"go-admin/apis/system/dict"
. "go-admin/apis/tools"
_ "go-admin/docs"
"go-admin/dto"
"go-admin/handler"
"go-admin/middleware"
"go-admin/models"
jwt "go-admin/pkg/jwtauth"
"go-admin/pkg/ws"
"mime"
@@ -110,11 +113,18 @@ func registerSysJobRouter(v1 *gin.RouterGroup) {
r := v1.Group("/sysjob")
{
r.GET("", sysjob.GetSysJobList)
r.GET("/:id", sysjob.GetSysJob)
r.POST("", sysjob.InsertSysJob)
r.PUT("", sysjob.UpdateSysJob)
r.DELETE("/:id", sysjob.DeleteSysJob)
//r.GET("", sysjob.GetSysJobList)
//r.GET("/:id", sysjob.GetSysJob)
//r.POST("", sysjob.InsertSysJob)
//r.PUT("", sysjob.UpdateSysJob)
//r.DELETE("/:id", sysjob.DeleteSysJob)
sysJob := &models.SysJob{}
r.GET("", actions.IndexAction(sysJob, new(dto.SysJobSearch)))
r.GET("/:id", actions.ViewAction(sysJob))
r.POST("", actions.CreateAction(sysJob))
r.PUT("", actions.UpdateAction(sysJob))
r.DELETE("/:id", actions.DeleteAction(sysJob))
}
v1.GET("/job/remove/:jobId", sysjob.RemoveJob)
+24 -1
View File
@@ -1,6 +1,7 @@
package tools
import (
"github.com/google/uuid"
"go-admin/tools/config"
"github.com/matchstalk/go-admin-core/search"
@@ -8,8 +9,30 @@ import (
)
type GeneralDelDto struct {
Id string `uri:"id" json:"id" validate:"required"`
Id string `uri:"id" json:"id" validate:"required"`
Ids []string `json:"ids"`
}
func (g GeneralDelDto) GetIds() []string {
ids := make([]string, 0)
if len(g.Ids) > 0 {
for _, id := range g.Ids {
if len(id) > 0 {
ids = append(ids, id)
}
}
} else {
if len(g.Id) > 0 {
ids = append(ids, g.Id)
}
}
if len(ids) <= 0 {
//方式全部删除
ids = append(ids, uuid.New().String())
}
return ids
}
type GeneralGetDto struct {
Id int `uri:"id" json:"id" validate:"required"`
}
+10
View File
@@ -0,0 +1,10 @@
package model
import "gorm.io/gorm/schema"
type ActiveRecord interface {
schema.Tabler
Generate() ActiveRecord
GetId() interface{}
GenerateList() interface{}
}