feat 修改usn类型为string
This commit is contained in:
83
internal/dao/repository/questions.go
Normal file
83
internal/dao/repository/questions.go
Normal file
@@ -0,0 +1,83 @@
|
||||
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-common/utils"
|
||||
"git.hlsq.asia/mmorpg/service-user/internal/dao/model"
|
||||
"git.hlsq.asia/mmorpg/service-user/internal/dao/query"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QuestionDao struct {
|
||||
ctx context.Context
|
||||
query *query.Query
|
||||
cache *redis.CacheClient
|
||||
}
|
||||
|
||||
func NewQuestionDao(ctx context.Context, cache ...*redis.CacheClient) *QuestionDao {
|
||||
dao := &QuestionDao{
|
||||
ctx: ctx,
|
||||
query: query.Use(mysql.GetDB(dbName)),
|
||||
}
|
||||
if len(cache) > 0 {
|
||||
dao.cache = cache[0]
|
||||
}
|
||||
return dao
|
||||
}
|
||||
|
||||
func (d *QuestionDao) Create(question *model.Question) error {
|
||||
err := d.query.Question.WithContext(d.ctx).
|
||||
Create(question)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *QuestionDao) FindByRandom() (*model.Question, error) {
|
||||
count, err := d.query.Question.WithContext(d.ctx).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()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return first, nil
|
||||
}
|
||||
|
||||
func (d *QuestionDao) FindBySn(sn string) (*model.Question, error) {
|
||||
if d.cache != nil {
|
||||
var question model.Question
|
||||
if ok := d.cache.Get(d.ctx, keyCacheBySn(sn, question.TableName()), &question); ok {
|
||||
return &question, nil
|
||||
}
|
||||
}
|
||||
first, err := d.query.Question.WithContext(d.ctx).
|
||||
Where(d.query.Question.Sn.Eq(sn)).
|
||||
First()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.cache != nil {
|
||||
d.cache.Set(d.ctx, keyCacheBySn(sn, first.TableName()), first, 5*time.Minute)
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
Reference in New Issue
Block a user