代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。