Skip to content

Commit f357c67

Browse files
committed
fix: 更新优化插件注册 api 和注册 menus 逻辑。
1 parent aa84605 commit f357c67

File tree

1 file changed

+35
-32
lines changed

1 file changed

+35
-32
lines changed
Lines changed: 35 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,53 @@
11
package utils
22

33
import (
4-
"fmt"
4+
"github.com/pkg/errors"
5+
"go.uber.org/zap"
6+
"gorm.io/gorm"
57

68
"github.com/flipped-aurora/gin-vue-admin/server/global"
79
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
810
)
911

10-
func RegisterApis(apis ...system.SysApi) {
11-
var count int64
12-
var apiPaths []string
13-
for i := range apis {
14-
apiPaths = append(apiPaths, apis[i].Path)
15-
}
16-
global.GVA_DB.Find(&[]system.SysApi{}, "path in (?)", apiPaths).Count(&count)
17-
if count > 0 {
18-
return
19-
}
20-
err := global.GVA_DB.Create(&apis).Error
12+
func RegisterApis( apis ...system.SysApi) {
13+
err := global.GVA_DB.Transaction(func(tx *gorm.DB) error {
14+
for _, api := range apis {
15+
err := tx.Model(system.SysApi{}).Where("path = ? AND method = ? AND api_group = ? ", api.Path, api.Method, api.ApiGroup).FirstOrCreate(&api).Error
16+
if err != nil {
17+
zap.L().Error("注册API失败", zap.Error(err), zap.String("api", api.Path), zap.String("method", api.Method), zap.String("apiGroup", api.ApiGroup))
18+
return err
19+
}
20+
}
21+
return nil
22+
})
2123
if err != nil {
22-
fmt.Println(err)
24+
zap.L().Error("注册API失败", zap.Error(err))
2325
}
2426
}
2527

26-
func RegisterMenus(menus ...system.SysBaseMenu) {
27-
var count int64
28-
var menuNames []string
28+
func RegisterMenus( menus ...system.SysBaseMenu) {
2929
parentMenu := menus[0]
3030
otherMenus := menus[1:]
31-
for i := range menus {
32-
menuNames = append(menuNames, menus[i].Name)
33-
}
34-
global.GVA_DB.Find(&[]system.SysBaseMenu{}, "name in (?)", menuNames).Count(&count)
35-
if count > 0 {
36-
return
37-
}
38-
err := global.GVA_DB.Create(&parentMenu).Error
39-
if err != nil {
40-
fmt.Println(err)
41-
}
42-
for i := range otherMenus {
31+
err := global.GVA_DB.Transaction(func(tx *gorm.DB) error {
32+
err := tx.Model(system.SysBaseMenu{}).Where("name = ? ", parentMenu.Name).FirstOrCreate(&parentMenu).Error
33+
if err != nil {
34+
zap.L().Error("注册菜单失败", zap.Error(err))
35+
return errors.Wrap(err, "注册菜单失败")
36+
}
4337
pid := parentMenu.ID
44-
otherMenus[i].ParentId = pid
45-
}
46-
err = global.GVA_DB.Create(&otherMenus).Error
38+
for i := range otherMenus {
39+
otherMenus[i].ParentId = pid
40+
err = tx.Model(system.SysBaseMenu{}).Where("name = ? ", otherMenus[i].Name).FirstOrCreate(&otherMenus[i]).Error
41+
if err != nil {
42+
zap.L().Error("注册菜单失败", zap.Error(err))
43+
return errors.Wrap(err, "注册菜单失败")
44+
}
45+
}
46+
47+
return nil
48+
})
4749
if err != nil {
48-
fmt.Println(err)
50+
zap.L().Error("注册菜单失败", zap.Error(err))
4951
}
52+
5053
}

0 commit comments

Comments
 (0)