From 47b89b674689a17b427a5a607e914ccc7f7bf91b Mon Sep 17 00:00:00 2001 From: "DESKTOP-V763RJ7\\Administrator" <835606593@qq.com> Date: Tue, 13 Jan 2026 11:27:57 +0800 Subject: [PATCH] =?UTF-8?q?feat=20=E5=A5=87=E6=80=AA=E7=9A=84=E7=9F=A5?= =?UTF-8?q?=E8=AF=861.0.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 2 +- go.sum | 4 +- internal/dao/model/categories.gen.go | 37 ++ internal/dao/model/questions.gen.go | 2 +- internal/dao/query/categories.gen.go | 347 ++++++++++++++++++ internal/dao/query/gen.go | 6 + internal/dao/query/questions.gen.go | 8 +- internal/dao/repository/categories.go | 64 ++++ internal/dao/repository/questions.go | 40 +- .../grpc_server/server/server_question.go | 54 ++- 10 files changed, 535 insertions(+), 29 deletions(-) create mode 100644 internal/dao/model/categories.gen.go create mode 100644 internal/dao/query/categories.gen.go create mode 100644 internal/dao/repository/categories.go diff --git a/go.mod b/go.mod index b9c9d2b..7530c0e 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module git.hlsq.asia/mmorpg/service-qgdzs go 1.23.1 require ( - git.hlsq.asia/mmorpg/service-common v0.0.0-20260112082258-b1e7d33940d7 + git.hlsq.asia/mmorpg/service-common v0.0.0-20260113014617-7812a3c669d7 github.com/judwhite/go-svc v1.2.1 google.golang.org/grpc v1.71.1 gorm.io/gen v0.3.27 diff --git a/go.sum b/go.sum index 4d8b631..6a84cac 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -git.hlsq.asia/mmorpg/service-common v0.0.0-20260112082258-b1e7d33940d7 h1:C3quCA54dyFgmlCVgJXx+0rNqa+JZgGggdotbvHAsnA= -git.hlsq.asia/mmorpg/service-common v0.0.0-20260112082258-b1e7d33940d7/go.mod h1:xv6m1I2jUA6mudKVznygpnzMoshBQarthHD1QnkW4qc= +git.hlsq.asia/mmorpg/service-common v0.0.0-20260113014617-7812a3c669d7 h1:sNZWEsAy4G5HEigdnnIHQ4eqmifN3rDPPApeTG4c4h4= +git.hlsq.asia/mmorpg/service-common v0.0.0-20260113014617-7812a3c669d7/go.mod h1:xv6m1I2jUA6mudKVznygpnzMoshBQarthHD1QnkW4qc= github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= diff --git a/internal/dao/model/categories.gen.go b/internal/dao/model/categories.gen.go new file mode 100644 index 0000000..826de21 --- /dev/null +++ b/internal/dao/model/categories.gen.go @@ -0,0 +1,37 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package model + +import ( + "time" + + "git.hlsq.asia/mmorpg/service-common/utils" + "gorm.io/gorm" +) + +const TableNameCategory = "categories" + +// Category mapped from table +type Category struct { + ID uint64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"` + Sn string `gorm:"column:sn;not null;comment:业务唯一编号" json:"sn"` // 业务唯一编号 + Category string `gorm:"column:category;not null;comment:分类" json:"category"` // 分类 + CreatedAt time.Time `gorm:"column:created_at;not null" json:"created_at"` + UpdatedAt time.Time `gorm:"column:updated_at;not null" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"deleted_at"` +} + +// TableName Category's table name +func (*Category) TableName() string { + return TableNameCategory +} + +// Auto sn +func (m *Category) BeforeCreate(_ *gorm.DB) error { + if m.Sn == "" { + m.Sn = utils.SnowflakeInstance().Generate().String() + } + return nil +} diff --git a/internal/dao/model/questions.gen.go b/internal/dao/model/questions.gen.go index d30d358..41da87f 100644 --- a/internal/dao/model/questions.gen.go +++ b/internal/dao/model/questions.gen.go @@ -22,7 +22,7 @@ type Question struct { Answer string `gorm:"column:answer;not null;comment:答案" json:"answer"` // 答案 Explanation string `gorm:"column:explanation;not null;comment:解析" json:"explanation"` // 解析 Difficulty int32 `gorm:"column:difficulty;not null;comment:难度分 0 - 100" json:"difficulty"` // 难度分 0 - 100 - Category string `gorm:"column:category;not null;comment:分类" json:"category"` // 分类 + CategorySn string `gorm:"column:category_sn;not null;comment:分类-唯一编号" json:"category_sn"` // 分类-唯一编号 CreatedAt time.Time `gorm:"column:created_at;not null" json:"created_at"` UpdatedAt time.Time `gorm:"column:updated_at;not null" json:"updated_at"` DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"deleted_at"` diff --git a/internal/dao/query/categories.gen.go b/internal/dao/query/categories.gen.go new file mode 100644 index 0000000..ec8e549 --- /dev/null +++ b/internal/dao/query/categories.gen.go @@ -0,0 +1,347 @@ +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. +// Code generated by gorm.io/gen. DO NOT EDIT. + +package query + +import ( + "context" + + "gorm.io/gorm" + "gorm.io/gorm/clause" + "gorm.io/gorm/schema" + + "gorm.io/gen" + "gorm.io/gen/field" + + "gorm.io/plugin/dbresolver" + + "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/model" +) + +func newCategory(db *gorm.DB, opts ...gen.DOOption) category { + _category := category{} + + _category.categoryDo.UseDB(db, opts...) + _category.categoryDo.UseModel(&model.Category{}) + + tableName := _category.categoryDo.TableName() + _category.ALL = field.NewAsterisk(tableName) + _category.ID = field.NewUint64(tableName, "id") + _category.Sn = field.NewString(tableName, "sn") + _category.Category = field.NewString(tableName, "category") + _category.CreatedAt = field.NewTime(tableName, "created_at") + _category.UpdatedAt = field.NewTime(tableName, "updated_at") + _category.DeletedAt = field.NewField(tableName, "deleted_at") + + _category.fillFieldMap() + + return _category +} + +type category struct { + categoryDo categoryDo + + ALL field.Asterisk + ID field.Uint64 + Sn field.String // 业务唯一编号 + Category field.String // 分类 + CreatedAt field.Time + UpdatedAt field.Time + DeletedAt field.Field + + fieldMap map[string]field.Expr +} + +func (c category) Table(newTableName string) *category { + c.categoryDo.UseTable(newTableName) + return c.updateTableName(newTableName) +} + +func (c category) As(alias string) *category { + c.categoryDo.DO = *(c.categoryDo.As(alias).(*gen.DO)) + return c.updateTableName(alias) +} + +func (c *category) updateTableName(table string) *category { + c.ALL = field.NewAsterisk(table) + c.ID = field.NewUint64(table, "id") + c.Sn = field.NewString(table, "sn") + c.Category = field.NewString(table, "category") + c.CreatedAt = field.NewTime(table, "created_at") + c.UpdatedAt = field.NewTime(table, "updated_at") + c.DeletedAt = field.NewField(table, "deleted_at") + + c.fillFieldMap() + + return c +} + +func (c *category) WithContext(ctx context.Context) *categoryDo { return c.categoryDo.WithContext(ctx) } + +func (c category) TableName() string { return c.categoryDo.TableName() } + +func (c category) Alias() string { return c.categoryDo.Alias() } + +func (c category) Columns(cols ...field.Expr) gen.Columns { return c.categoryDo.Columns(cols...) } + +func (c *category) GetFieldByName(fieldName string) (field.OrderExpr, bool) { + _f, ok := c.fieldMap[fieldName] + if !ok || _f == nil { + return nil, false + } + _oe, ok := _f.(field.OrderExpr) + return _oe, ok +} + +func (c *category) fillFieldMap() { + c.fieldMap = make(map[string]field.Expr, 6) + c.fieldMap["id"] = c.ID + c.fieldMap["sn"] = c.Sn + c.fieldMap["category"] = c.Category + c.fieldMap["created_at"] = c.CreatedAt + c.fieldMap["updated_at"] = c.UpdatedAt + c.fieldMap["deleted_at"] = c.DeletedAt +} + +func (c category) clone(db *gorm.DB) category { + c.categoryDo.ReplaceConnPool(db.Statement.ConnPool) + return c +} + +func (c category) replaceDB(db *gorm.DB) category { + c.categoryDo.ReplaceDB(db) + return c +} + +type categoryDo struct{ gen.DO } + +func (c categoryDo) Debug() *categoryDo { + return c.withDO(c.DO.Debug()) +} + +func (c categoryDo) WithContext(ctx context.Context) *categoryDo { + return c.withDO(c.DO.WithContext(ctx)) +} + +func (c categoryDo) ReadDB() *categoryDo { + return c.Clauses(dbresolver.Read) +} + +func (c categoryDo) WriteDB() *categoryDo { + return c.Clauses(dbresolver.Write) +} + +func (c categoryDo) Session(config *gorm.Session) *categoryDo { + return c.withDO(c.DO.Session(config)) +} + +func (c categoryDo) Clauses(conds ...clause.Expression) *categoryDo { + return c.withDO(c.DO.Clauses(conds...)) +} + +func (c categoryDo) Returning(value interface{}, columns ...string) *categoryDo { + return c.withDO(c.DO.Returning(value, columns...)) +} + +func (c categoryDo) Not(conds ...gen.Condition) *categoryDo { + return c.withDO(c.DO.Not(conds...)) +} + +func (c categoryDo) Or(conds ...gen.Condition) *categoryDo { + return c.withDO(c.DO.Or(conds...)) +} + +func (c categoryDo) Select(conds ...field.Expr) *categoryDo { + return c.withDO(c.DO.Select(conds...)) +} + +func (c categoryDo) Where(conds ...gen.Condition) *categoryDo { + return c.withDO(c.DO.Where(conds...)) +} + +func (c categoryDo) Order(conds ...field.Expr) *categoryDo { + return c.withDO(c.DO.Order(conds...)) +} + +func (c categoryDo) Distinct(cols ...field.Expr) *categoryDo { + return c.withDO(c.DO.Distinct(cols...)) +} + +func (c categoryDo) Omit(cols ...field.Expr) *categoryDo { + return c.withDO(c.DO.Omit(cols...)) +} + +func (c categoryDo) Join(table schema.Tabler, on ...field.Expr) *categoryDo { + return c.withDO(c.DO.Join(table, on...)) +} + +func (c categoryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *categoryDo { + return c.withDO(c.DO.LeftJoin(table, on...)) +} + +func (c categoryDo) RightJoin(table schema.Tabler, on ...field.Expr) *categoryDo { + return c.withDO(c.DO.RightJoin(table, on...)) +} + +func (c categoryDo) Group(cols ...field.Expr) *categoryDo { + return c.withDO(c.DO.Group(cols...)) +} + +func (c categoryDo) Having(conds ...gen.Condition) *categoryDo { + return c.withDO(c.DO.Having(conds...)) +} + +func (c categoryDo) Limit(limit int) *categoryDo { + return c.withDO(c.DO.Limit(limit)) +} + +func (c categoryDo) Offset(offset int) *categoryDo { + return c.withDO(c.DO.Offset(offset)) +} + +func (c categoryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *categoryDo { + return c.withDO(c.DO.Scopes(funcs...)) +} + +func (c categoryDo) Unscoped() *categoryDo { + return c.withDO(c.DO.Unscoped()) +} + +func (c categoryDo) Create(values ...*model.Category) error { + if len(values) == 0 { + return nil + } + return c.DO.Create(values) +} + +func (c categoryDo) CreateInBatches(values []*model.Category, batchSize int) error { + return c.DO.CreateInBatches(values, batchSize) +} + +// Save : !!! underlying implementation is different with GORM +// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values) +func (c categoryDo) Save(values ...*model.Category) error { + if len(values) == 0 { + return nil + } + return c.DO.Save(values) +} + +func (c categoryDo) First() (*model.Category, error) { + if result, err := c.DO.First(); err != nil { + return nil, err + } else { + return result.(*model.Category), nil + } +} + +func (c categoryDo) Take() (*model.Category, error) { + if result, err := c.DO.Take(); err != nil { + return nil, err + } else { + return result.(*model.Category), nil + } +} + +func (c categoryDo) Last() (*model.Category, error) { + if result, err := c.DO.Last(); err != nil { + return nil, err + } else { + return result.(*model.Category), nil + } +} + +func (c categoryDo) Find() ([]*model.Category, error) { + result, err := c.DO.Find() + return result.([]*model.Category), err +} + +func (c categoryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Category, err error) { + buf := make([]*model.Category, 0, batchSize) + err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error { + defer func() { results = append(results, buf...) }() + return fc(tx, batch) + }) + return results, err +} + +func (c categoryDo) FindInBatches(result *[]*model.Category, batchSize int, fc func(tx gen.Dao, batch int) error) error { + return c.DO.FindInBatches(result, batchSize, fc) +} + +func (c categoryDo) Attrs(attrs ...field.AssignExpr) *categoryDo { + return c.withDO(c.DO.Attrs(attrs...)) +} + +func (c categoryDo) Assign(attrs ...field.AssignExpr) *categoryDo { + return c.withDO(c.DO.Assign(attrs...)) +} + +func (c categoryDo) Joins(fields ...field.RelationField) *categoryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Joins(_f)) + } + return &c +} + +func (c categoryDo) Preload(fields ...field.RelationField) *categoryDo { + for _, _f := range fields { + c = *c.withDO(c.DO.Preload(_f)) + } + return &c +} + +func (c categoryDo) FirstOrInit() (*model.Category, error) { + if result, err := c.DO.FirstOrInit(); err != nil { + return nil, err + } else { + return result.(*model.Category), nil + } +} + +func (c categoryDo) FirstOrCreate() (*model.Category, error) { + if result, err := c.DO.FirstOrCreate(); err != nil { + return nil, err + } else { + return result.(*model.Category), nil + } +} + +func (c categoryDo) FindByPage(offset int, limit int) (result []*model.Category, count int64, err error) { + result, err = c.Offset(offset).Limit(limit).Find() + if err != nil { + return + } + + if size := len(result); 0 < limit && 0 < size && size < limit { + count = int64(size + offset) + return + } + + count, err = c.Offset(-1).Limit(-1).Count() + return +} + +func (c categoryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) { + count, err = c.Count() + if err != nil { + return + } + + err = c.Offset(offset).Limit(limit).Scan(result) + return +} + +func (c categoryDo) Scan(result interface{}) (err error) { + return c.DO.Scan(result) +} + +func (c categoryDo) Delete(models ...*model.Category) (result gen.ResultInfo, err error) { + return c.DO.Delete(models) +} + +func (c *categoryDo) withDO(do gen.Dao) *categoryDo { + c.DO = *do.(*gen.DO) + return c +} diff --git a/internal/dao/query/gen.go b/internal/dao/query/gen.go index 1c33cf3..f9d8ca8 100644 --- a/internal/dao/query/gen.go +++ b/internal/dao/query/gen.go @@ -18,6 +18,7 @@ import ( func Use(db *gorm.DB, opts ...gen.DOOption) *Query { return &Query{ db: db, + Category: newCategory(db, opts...), Question: newQuestion(db, opts...), } } @@ -25,6 +26,7 @@ func Use(db *gorm.DB, opts ...gen.DOOption) *Query { type Query struct { db *gorm.DB + Category category Question question } @@ -33,6 +35,7 @@ func (q *Query) Available() bool { return q.db != nil } func (q *Query) clone(db *gorm.DB) *Query { return &Query{ db: db, + Category: q.Category.clone(db), Question: q.Question.clone(db), } } @@ -48,16 +51,19 @@ func (q *Query) WriteDB() *Query { func (q *Query) ReplaceDB(db *gorm.DB) *Query { return &Query{ db: db, + Category: q.Category.replaceDB(db), Question: q.Question.replaceDB(db), } } type queryCtx struct { + Category *categoryDo Question *questionDo } func (q *Query) WithContext(ctx context.Context) *queryCtx { return &queryCtx{ + Category: q.Category.WithContext(ctx), Question: q.Question.WithContext(ctx), } } diff --git a/internal/dao/query/questions.gen.go b/internal/dao/query/questions.gen.go index efc265e..477adbf 100644 --- a/internal/dao/query/questions.gen.go +++ b/internal/dao/query/questions.gen.go @@ -34,7 +34,7 @@ func newQuestion(db *gorm.DB, opts ...gen.DOOption) question { _question.Answer = field.NewString(tableName, "answer") _question.Explanation = field.NewString(tableName, "explanation") _question.Difficulty = field.NewInt32(tableName, "difficulty") - _question.Category = field.NewString(tableName, "category") + _question.CategorySn = field.NewString(tableName, "category_sn") _question.CreatedAt = field.NewTime(tableName, "created_at") _question.UpdatedAt = field.NewTime(tableName, "updated_at") _question.DeletedAt = field.NewField(tableName, "deleted_at") @@ -55,7 +55,7 @@ type question struct { Answer field.String // 答案 Explanation field.String // 解析 Difficulty field.Int32 // 难度分 0 - 100 - Category field.String // 分类 + CategorySn field.String // 分类-唯一编号 CreatedAt field.Time UpdatedAt field.Time DeletedAt field.Field @@ -82,7 +82,7 @@ func (q *question) updateTableName(table string) *question { q.Answer = field.NewString(table, "answer") q.Explanation = field.NewString(table, "explanation") q.Difficulty = field.NewInt32(table, "difficulty") - q.Category = field.NewString(table, "category") + q.CategorySn = field.NewString(table, "category_sn") q.CreatedAt = field.NewTime(table, "created_at") q.UpdatedAt = field.NewTime(table, "updated_at") q.DeletedAt = field.NewField(table, "deleted_at") @@ -118,7 +118,7 @@ func (q *question) fillFieldMap() { q.fieldMap["answer"] = q.Answer q.fieldMap["explanation"] = q.Explanation q.fieldMap["difficulty"] = q.Difficulty - q.fieldMap["category"] = q.Category + q.fieldMap["category_sn"] = q.CategorySn q.fieldMap["created_at"] = q.CreatedAt q.fieldMap["updated_at"] = q.UpdatedAt q.fieldMap["deleted_at"] = q.DeletedAt diff --git a/internal/dao/repository/categories.go b/internal/dao/repository/categories.go new file mode 100644 index 0000000..ddcc8ad --- /dev/null +++ b/internal/dao/repository/categories.go @@ -0,0 +1,64 @@ +package repository + +import ( + "context" + "git.hlsq.asia/mmorpg/service-common/db/mysql" + "git.hlsq.asia/mmorpg/service-common/db/redis" + "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/model" + "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/query" +) + +type CategoryDao struct { + ctx context.Context + query *query.Query + cache *redis.CacheClient +} + +func NewCategoryDao(ctx context.Context, cache ...*redis.CacheClient) *CategoryDao { + dao := &CategoryDao{ + ctx: ctx, + query: query.Use(mysql.GetDB(dbName)), + } + if len(cache) > 0 { + dao.cache = cache[0] + } + return dao +} + +func (d *CategoryDao) Create(category *model.Category) (*model.Category, error) { + err := d.query.Category.WithContext(d.ctx). + Create(category) + return category, err +} + +func (d *CategoryDao) FindAll() ([]*model.Category, error) { + find, err := d.query.Category.WithContext(d.ctx). + Select(d.query.Category.Sn, d.query.Category.Category). + Find() + if err != nil { + return nil, err + } + return find, nil +} + +func (d *CategoryDao) FindNameBySn(sn string) (string, error) { + first, err := d.query.Category.WithContext(d.ctx). + Select(d.query.Category.Category). + Where(d.query.Category.Sn.Eq(sn)). + First() + if err != nil { + return "", err + } + return first.Category, nil +} + +func (d *CategoryDao) FindSnByName(category string) (string, error) { + first, err := d.query.Category.WithContext(d.ctx). + Select(d.query.Category.Sn). + Where(d.query.Category.Category.Eq(category)). + First() + if err != nil { + return "", err + } + return first.Sn, nil +} diff --git a/internal/dao/repository/questions.go b/internal/dao/repository/questions.go index 30c3c6f..702ef0f 100644 --- a/internal/dao/repository/questions.go +++ b/internal/dao/repository/questions.go @@ -28,23 +28,27 @@ func NewQuestionDao(ctx context.Context, cache ...*redis.CacheClient) *QuestionD return dao } -func (d *QuestionDao) Create(question *model.Question) error { +func (d *QuestionDao) Create(question *model.Question) (*model.Question, error) { err := d.query.Question.WithContext(d.ctx). Create(question) - return err + return question, err } -func (d *QuestionDao) FindByRandom() (*model.Question, error) { - count, err := d.query.Question.WithContext(d.ctx).Count() +func (d *QuestionDao) FindByRandom(categorySn string) (*model.Question, error) { + q := d.query.Question.WithContext(d.ctx) + if categorySn != "" { + q = q.Where(d.query.Question.CategorySn.Eq(categorySn)) + } + + count, err := q.Count() if err != nil { return nil, err } if count == 0 { return nil, gorm.ErrRecordNotFound } - first, err := d.query.Question.WithContext(d.ctx). - Offset(utils.RandInt(0, int(count-1))). - First() + + first, err := q.Offset(utils.RandInt(0, int(count-1))).First() if err != nil { return nil, err } @@ -70,14 +74,22 @@ func (d *QuestionDao) FindBySn(sn string) (*model.Question, error) { return first, nil } -func (d *QuestionDao) FindCategory() ([]string, error) { - var categories []string - err := d.query.Question.WithContext(d.ctx). - Select(d.query.Question.Category). - Distinct(). - Scan(&categories) +func (d *QuestionDao) FindByCategory(categorySn string) (*model.Question, error) { + count, err := d.query.Question.WithContext(d.ctx). + Where(d.query.Question.CategorySn.Eq(categorySn)). + Count() if err != nil { return nil, err } - return categories, nil + if count == 0 { + return nil, gorm.ErrRecordNotFound + } + first, err := d.query.Question.WithContext(d.ctx). + Where(d.query.Question.CategorySn.Eq(categorySn)). + Offset(utils.RandInt(0, int(count-1))). + First() + if err != nil { + return nil, err + } + return first, nil } diff --git a/internal/grpc_server/server/server_question.go b/internal/grpc_server/server/server_question.go index b2b9b51..1cb14e0 100644 --- a/internal/grpc_server/server/server_question.go +++ b/internal/grpc_server/server/server_question.go @@ -3,6 +3,7 @@ package server import ( "context" "encoding/json" + "errors" "fmt" "git.hlsq.asia/mmorpg/service-common/db/redis" "git.hlsq.asia/mmorpg/service-common/log" @@ -10,6 +11,7 @@ import ( "git.hlsq.asia/mmorpg/service-qgdzs/internal/ai" "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/model" "git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/repository" + "gorm.io/gorm" "time" ) @@ -68,7 +70,8 @@ type Question struct { } func (s *Server) GenerateQuestion(ctx context.Context, req *grpc_pb.GenerateQuestionReq) (*grpc_pb.GenerateQuestionResp, error) { - category, err := repository.NewQuestionDao(ctx).FindCategory() + categoryDao := repository.NewCategoryDao(ctx, redis.GetCacheClient()) + category, err := categoryDao.FindAll() if err != nil { log.Errorf("GenerateQuestion FindCategory error: %v", err) return nil, err @@ -105,12 +108,28 @@ func (s *Server) GenerateQuestion(ctx context.Context, req *grpc_pb.GenerateQues questionDao := repository.NewQuestionDao(ctx, redis.GetCacheClient()) for _, q := range question { marshal, _ := json.Marshal(q.Options) - if err = questionDao.Create(&model.Question{ + categorySn, err := categoryDao.FindSnByName(q.Category) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + cat, err := categoryDao.Create(&model.Category{ + Category: q.Category, + }) + if err != nil { + log.Errorf("GenerateQuestion CreateCategory error: %v", err) + continue + } + categorySn = cat.Sn + } else { + log.Errorf("GenerateQuestion FindSnByName error: %v", err) + continue + } + } + if _, err = questionDao.Create(&model.Question{ Question: q.Question, Options: string(marshal), Answer: q.Answer, Explanation: q.Explanation, - Category: q.Category, + CategorySn: categorySn, Difficulty: q.Difficulty, }); err != nil { log.Errorf("GenerateQuestion Create error: %v", err) @@ -121,7 +140,7 @@ func (s *Server) GenerateQuestion(ctx context.Context, req *grpc_pb.GenerateQues } func (s *Server) GetQuestion(ctx context.Context, req *grpc_pb.GetQuestionReq) (*grpc_pb.GetQuestionResp, error) { - question, err := repository.NewQuestionDao(ctx).FindByRandom() + question, err := repository.NewQuestionDao(ctx).FindByRandom(req.CategorySn) if err != nil { log.Errorf("GetQuestion error: %v", err) return nil, err @@ -131,10 +150,13 @@ func (s *Server) GetQuestion(ctx context.Context, req *grpc_pb.GetQuestionReq) ( log.Errorf("GetQuestion json.Unmarshal error: %v, data: %v", err, question.Options) return nil, err } + category, _ := repository.NewCategoryDao(ctx).FindNameBySn(question.CategorySn) return &grpc_pb.GetQuestionResp{ - Sn: question.Sn, - Question: question.Question, - Options: options, + Sn: question.Sn, + Question: question.Question, + Options: options, + Category: category, + Difficulty: question.Difficulty, }, nil } @@ -154,3 +176,21 @@ func (s *Server) AnswerQuestion(ctx context.Context, req *grpc_pb.AnswerQuestion Explanation: question.Explanation, }, nil } + +func (s *Server) GetAllCategory(ctx context.Context, req *grpc_pb.GetAllCategoryReq) (*grpc_pb.GetAllCategoryResp, error) { + categoryList, err := repository.NewCategoryDao(ctx).FindAll() + if err != nil { + log.Errorf("GetAllCategory error: %v", err) + return nil, err + } + categories := make([]*grpc_pb.GetAllCategoryItem, 0) + for _, category := range categoryList { + categories = append(categories, &grpc_pb.GetAllCategoryItem{ + Sn: category.Sn, + Category: category.Category, + }) + } + return &grpc_pb.GetAllCategoryResp{ + Categories: categories, + }, nil +}