Randomly retrieving several words is similar to fetching a paginated list of words:
- No paginated query, instead use random query;
- No fuzzy query;
- The returned data is basically the same.
Add 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:"Randomly Retrieve Word List" tags:"Words"`
Limit uint `json:"limit" v:"between:1,300" dc:"Limit number, default 50"`
}
type RandListRes struct {
List []List `json:"list"`
}
RandListReq
provides a Limit
field to specify the number of items to retrieve, ranging from 1-300
. RandListRes
uses the same data structure as the paginated word list but lacks the Total
field.
words/rand
is an exact match with higher priority than the word detail interface:words/{id}
.
Write 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 Randomly retrieve a few words
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
is a random query method provided by GoFrame ORM
, and the Limit
method is used to restrict the number of queries.
Controller Calls 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
}
API Testing
Prepare some test data and conduct tests; detailed explanations are omitted here for brevity.
$ 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": [
...
]
}
}