Skip to content

Commit

Permalink
✨重构代码
Browse files Browse the repository at this point in the history
  • Loading branch information
Sakura-LF committed Oct 16, 2024
1 parent 759746f commit 91f136b
Show file tree
Hide file tree
Showing 7 changed files with 83 additions and 11 deletions.
13 changes: 13 additions & 0 deletions configs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type Config struct {
SiteInfo SiteInfo `mapstructure:"siteInfo" json:"siteInfo" yaml:"siteInfo"`
Email EmailConfig `mapstructure:"email" json:"email" yaml:"email"`
Jwt Jwt `mapstructure:"jwt" yaml:"jwt" json:"jwt"`
AI AIConfig `mapstructure:"ai" json:"ai" yaml:"ai"`
}

type Data struct {
Expand Down Expand Up @@ -115,3 +116,15 @@ type Jwt struct {
Expires time.Duration `yaml:"expires" json:"expires"`
Issuer string `yaml:"issuer" json:"issuer"`
}

type AIConfig struct {
Model string `mapstructure:"model" json:"model"`
ProxyURL string `mapstructure:"proxyUrl" json:"proxyUrl"`
APIKey string `mapstructure:"apiKey" json:"apiKey"`
ChatScope int `mapstructure:"chatScope" json:"chatScope"`
CreateRoleScope int `mapstructure:"createRoleScope" json:"createRoleScope"` // 创建角色的积分消耗
UpdateRoleScope int `mapstructure:"updateRoleScope" json:"updateRoleScope"` // 更新角色的积分消耗
DeleteRoleScope int `mapstructure:"deleteRoleScope" json:"deleteRoleScope"` // 删除角色的积分消耗
RecommendRoleScope int `mapstructure:"recommendRoleScope" json:"recommendRoleScope"` // 推荐角色成功的积分赠送
RegisterUserScope int `mapstructure:"registerUserScope" json:"registerUserScope"` // 注册用户成功的积分赠送
}
15 changes: 9 additions & 6 deletions internal/api/aiRole/aiRoleCreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package aiRole
import (
"AI_Server/common/jwt"
"AI_Server/internal/data/mysql/aiRole"
"AI_Server/internal/data/mysql/user"
"AI_Server/utils/res"
"github.com/gofiber/fiber/v3"
)
Expand All @@ -21,14 +22,16 @@ func (role *AiRoleApi) RoleCreate(c fiber.Ctx) error {
if err != nil {
return res.FailWithMsgAndReason(c, "请求参数错误", err.Error())
}

claims := c.Locals("claims").(jwt.PayLoad)

if _, err = aiRole.FindAiRole(claims.UserId, req.Title); err != nil {
return res.FailWithMsgAndReason(c, "角色已存在,同一个用户不能创建相同名称的角色", err.Error())
// 验证角色是否存在
findUser, err := user.FindUserByUserId(claims.UserId)
if err != nil {
return res.FailWithMsgAndReason(c, "用户不存在", err.Error())
}
if _, err = aiRole.CreateAiRole(findUser, req.Title, req.Avatar, req.Category, req.Abstract, req.Prompt); err != nil {
return res.FailWithMsgAndReason(c, "创建角色失败", err.Error())
}

// 开启事务写入

return nil
return res.OkWithMsg(c, "创建角色成功")
}
44 changes: 42 additions & 2 deletions internal/data/mysql/aiRole/aiRole.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,56 @@ package aiRole

import (
"AI_Server/init/data"
"AI_Server/internal/data/mysql/user"
"AI_Server/internal/modeles"
"errors"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)

func CreateAiRole() {

// CreateAiRole 用于创建一个角色
func CreateAiRole(findUser *modeles.User, title, avatar, category, abstract, prompt string) (*modeles.AiRole, error) {
// 1.查找该用户是否创建了相同的角色
if _, err := FindAiRole(findUser.ID, title); err == nil {
//if errors.Is(err, gorm.ErrRecordNotFound) {
// // 角色不存在,继续创建角色
// log.Info().Msg("角色不存在,创建角色")
//} else if err != nil {
// log.Info().Msg("角色已存在")
// return nil, errors.New("角色已存在,同一个用户不能创建相同名称的角色")
//}
return nil, errors.New("角色已存在,同一个用户不能创建相同名称的角色")
}
// 2.构建角色
aiRole := &modeles.AiRole{
UserID: findUser.ID,
Title: title,
Avatar: avatar,
Category: category,
Abstract: abstract,
Prompt: prompt,
}
// 3.开启事务创建角色
err := data.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(aiRole).Error; err != nil {
return err
}
// 4.扣除用户的积分
if err := user.DeductUserPoints(tx, findUser, 100); err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return aiRole, nil
}

// FindAiRole 用于寻找该用户是否创建了相同的角色
func FindAiRole(userID uint, title string) (*modeles.AiRole, error) {
aiRole := &modeles.AiRole{}
log.Info().Any("userId", userID).Any("title", title).Msg("查找角色")
if err := data.DB.Take(aiRole, "user_id = ? and title = ?", userID, title).Error; err != nil {
return nil, err
}
Expand Down
14 changes: 14 additions & 0 deletions internal/data/mysql/user/user.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package user

import (
"AI_Server/init/conf"
"AI_Server/init/data"
"AI_Server/internal/modeles"
"AI_Server/utils/rand"
"errors"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)

func CreateUser(registerSource modeles.RegisterSource, val string) (*modeles.User, error) {
Expand Down Expand Up @@ -59,3 +61,15 @@ func FindUserByUserId(id uint) (*modeles.User, error) {
}
return user, nil
}

func DeductUserPoints(tx *gorm.DB, user *modeles.User, point int) error {
newPoints := user.Scope - conf.GlobalConfig.AI.CreateRoleScope
if newPoints < 0 {
return errors.New("积分不足")
}
// 开启数据库事务
if err := tx.Model(user).Update("scope", newPoints).Error; err != nil {
return err
}
return nil
}
4 changes: 2 additions & 2 deletions internal/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (

func AuthToken() fiber.Handler {
return func(c fiber.Ctx) error {
log.Info().Msg("Test")
token := c.Get("Authorization")
log.Info().Msg(token)
if token == "" {
return res.FailWithMsg(c, "未携带 Token 请先登录")
}
Expand All @@ -20,7 +20,7 @@ func AuthToken() fiber.Handler {
return res.FailWithMsg(c, "Token 解析失败")
}
c.Locals("claims", claims.PayLoad)

log.Info().Msg("Token 认证通过")
return c.Next()
}
}
Expand Down
3 changes: 2 additions & 1 deletion internal/routers/aiRoleRouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package routers

import (
"AI_Server/internal/api/aiRole"
"AI_Server/internal/middleware"
"github.com/gofiber/fiber/v3"
)

func AiRoleRouter(r fiber.Router) {
app := aiRole.AiRoleApi{}
r.Post("/ai/role/create", app.RoleCreate)
r.Post("/ai/role/create", app.RoleCreate, middleware.AuthToken())
}
1 change: 1 addition & 0 deletions internal/routers/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func InitRouters() {

SettingRouter(apiRouter)
UserRouter(apiRouter)
AiRoleRouter(apiRouter)

log.Fatal().Err(app.Listen(conf.GlobalConfig.Server.Http.Addr, fiber.ListenConfig{
EnablePrefork: false,
Expand Down

0 comments on commit 91f136b

Please sign in to comment.