1 Star 0 Fork 0

igo/pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
callback.go 2.17 KB
一键复制 编辑 原始数据 按行查看 历史
layte.xiao 提交于 2022-10-15 11:20 . init
package xgorm
import (
"errors"
"fmt"
"gorm.io/gorm"
"strings"
)
type Callback struct {
Name string
Action string
Before string
After string
Callback func(db *gorm.DB)
}
func (c Callback) Valid() error {
if c.Name == "" {
return errors.New("db callback name is nil")
}
if c.Callback == nil {
return errors.New("db callback is nil")
}
if c.Action == "" {
return errors.New("db action is nil")
}
return nil
}
func RegisterCallBack(db *gorm.DB, callbacks ...Callback) error {
if db == nil || len(callbacks) == 0 {
return nil
}
errs := make([]error, 0)
for _, callback := range callbacks {
if err := callback.Valid(); err != nil {
errs = append(errs, fmt.Errorf("callback: %s, err: %v", callback.Name, err))
continue
}
var processor = db.Callback().Create()
if strings.ToLower(callback.Action) == "update" {
processor = db.Callback().Update()
}
if strings.ToLower(callback.Action) == "delete" {
processor = db.Callback().Delete()
}
if strings.ToLower(callback.Action) == "query" {
processor = db.Callback().Query()
}
if strings.ToLower(callback.Action) == "row" {
processor = db.Callback().Row()
}
if strings.ToLower(callback.Action) == "raw" {
processor = db.Callback().Raw()
}
if processor == db.Callback().Create() && strings.ToLower(callback.Action) != "create" {
errs = append(errs, fmt.Errorf("callback: %s, db action invalid", callback.Name))
continue
}
if processor.Get(callback.Name) != nil {
//errs = append(errs, fmt.Errorf("callback: %s, already registered", callback.Name))
continue
}
if callback.Before != "" {
if err := processor.Before(callback.Before).Register(callback.Name, callback.Callback); err != nil {
errs = append(errs, err)
}
}
if callback.After != "" {
if err := processor.After(callback.After).Register(callback.Name, callback.Callback); err != nil {
errs = append(errs, err)
}
}
if callback.Before == "" && callback.After == "" {
if err := processor.Register(callback.Name, callback.Callback); err != nil {
errs = append(errs, err)
}
}
}
if len(errs) > 0 {
return fmt.Errorf("db register callback errs: %v", errs)
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/igolang/pkg.git
git@gitee.com:igolang/pkg.git
igolang
pkg
pkg
v1.19.8

搜索帮助

0d507c66 1850385 C8b1a773 1850385