随机获取若干单词与获取单词分页列表大同小异:
- 没有分页查询,转而使用随机查询;
- 没有模糊查询;
- 返回的数据基本一致。
添加Api
api/words/v1/learn_words.go
package v1
import (
"github.com/gogf/gf/v2/frame/g"
"star/internal/model"
)
type RandListReq struct {
g.Meta `path:"words/rand" method:"get" sm:"随机获取单词列表" tags:"单词"`
Limit uint `json:"limit" v:"between:1,300" dc:"限制个数,默认50"`
}
type RandListRes struct {
List []List `json:"list"`
}
RandListReq
提供Limit
字段,表示想要获取的个数,范围在1-300
。RandListRes
使用与单词分页列表一样的数据结构,但是少了Total
字段。
words/rand
是一种精确匹配,它的优先级要高于单词详情接口:words/{id}
。
编写Logic
internal/controller/words/words_v1_rand_list.go
package words
import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"star/internal/dao"
"star/internal/model"
"star/internal/model/entity"
)
// Rand 随机若干获取单词
func Rand(ctx context.Context, uid, limit uint) ([]entity.Words, error) {
if limit <= 0 {
limit = 50
}
var (
list = make([]entity.Words, limit)
err error
)
db := dao.Words.Ctx(ctx)
if uid > 0 {
db = db.Where("uid", uid)
}
err = db.Limit(int(limit)).OrderRandom().Scan(&list)
return list, err
}
OrderRandom
是GoFrame ORM
提供的随机查询方法,Limit
方法用于限制查询个数
Controller调用Logic
internal/logic/words/learn_words.go
package words
import (
"context"
"star/api/words/v1"
"star/internal/logic/users"
"star/internal/logic/words"
"star/internal/model"
)
func (c *ControllerV1) RandList(ctx context.Context, req *v1.RandListReq) (res *v1.RandListRes, err error) {
uid, err := users.GetUid(ctx)
if err != nil {
return nil, err
}
wordList, err := words.Rand(ctx, uid, req.Limit)
if err != nil {
return nil, err
}
var list []v1.List
for _, v := range wordList {
list = append(list, v1.List{
Id: v.Id,
Word: v.Word,
Definition: v.Definition,
ProficiencyLevel: model.ProficiencyLevel(v.ProficiencyLevel),
})
}
return &v1.RandListRes{
List: list,
}, nil
}
接口测试
准备一些测试数据并测试,这里为了节省篇幅就不再详细介绍了。
$ curl -X GET http://127.0.0.1:8000/v1/words/rand \
-H "Authorization: eyJhbGci...5U" \
-H "Content-Type: application/json" \
{
"code": 0,
"message": "",
"data": {
"list": [
...
]
}
}