57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
package utils
|
|
|
|
import (
|
|
"github.com/pkg/errors"
|
|
"go.uber.org/zap"
|
|
"gorm.io/gorm"
|
|
|
|
"kra/internal/data/model"
|
|
)
|
|
|
|
// RegisterApis 注册API到数据库
|
|
func RegisterApis(db *gorm.DB, apis ...model.SysAPI) {
|
|
err := db.Transaction(func(tx *gorm.DB) error {
|
|
for _, api := range apis {
|
|
err := tx.Model(model.SysAPI{}).Where("path = ? AND method = ? AND api_group = ? ", api.Path, api.Method, api.APIGroup).FirstOrCreate(&api).Error
|
|
if err != nil {
|
|
zap.L().Error("注册API失败", zap.Error(err), zap.String("api", api.Path), zap.String("method", api.Method), zap.String("apiGroup", api.APIGroup))
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
zap.L().Error("注册API失败", zap.Error(err))
|
|
}
|
|
}
|
|
|
|
// RegisterMenus 注册菜单到数据库
|
|
func RegisterMenus(db *gorm.DB, menus ...model.SysBaseMenu) {
|
|
if len(menus) == 0 {
|
|
return
|
|
}
|
|
parentMenu := menus[0]
|
|
otherMenus := menus[1:]
|
|
err := db.Transaction(func(tx *gorm.DB) error {
|
|
err := tx.Model(model.SysBaseMenu{}).Where("name = ? ", parentMenu.Name).FirstOrCreate(&parentMenu).Error
|
|
if err != nil {
|
|
zap.L().Error("注册菜单失败", zap.Error(err))
|
|
return errors.Wrap(err, "注册菜单失败")
|
|
}
|
|
pid := parentMenu.ID
|
|
for i := range otherMenus {
|
|
otherMenus[i].ParentID = pid
|
|
err = tx.Model(model.SysBaseMenu{}).Where("name = ? ", otherMenus[i].Name).FirstOrCreate(&otherMenus[i]).Error
|
|
if err != nil {
|
|
zap.L().Error("注册菜单失败", zap.Error(err))
|
|
return errors.Wrap(err, "注册菜单失败")
|
|
}
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
zap.L().Error("注册菜单失败", zap.Error(err))
|
|
}
|
|
}
|