Skip to main content
Version: 2.7.x(Latest)

设置掌握程度的功能本质上是一种编辑,只改变ProficiencyLevel一个字段,所以这里使用PATCH方式比PUT更为合适。

添加Api


api/words/v1/learn_words.go

...

type SetLevelReq struct {
g.Meta `path:"words/{id}/level" method:"patch"`
Id uint `json:"id" v:"required"`
Level model.ProficiencyLevel `json:"level" v:"required|between:1,5"`
}

type SetLevelRes struct {
}

words/{id}/levelwords/level/{id}这两种路由风格均可,但是前者更符合资源层级关系,推荐使用。

编写Logic


internal/controller/words/words_v1_set_level.go

...

// SetLevel 设置单词熟练度
func SetLevel(ctx context.Context, uid, id uint, level model.ProficiencyLevel) error {
if level < 0 || level > 5 {
return gerror.New("熟练度值不合法")
}

db := dao.Words.Ctx(ctx)
if uid > 0 {
db = db.Where("uid", uid)
}

_, err := db.Data("proficiency_level", level).Where("id", id).Update()
return err
}

为了防止数据异常,我们要在入库前检测等级是否在1-5之间。

Controller调用Logic


internal/logic/words/learn_words.go

package words  

import (
"context"

"star/api/words/v1"
"star/internal/logic/users"
"star/internal/logic/words"
)

func (c *ControllerV1) SetLevel(ctx context.Context, req *v1.SetLevelReq) (res *v1.SetLevelRes, err error) {
uid, err := users.GetUid(ctx)
if err != nil {
return nil, err
}

err = words.SetLevel(ctx, uid, req.Id, req.Level)
return nil, err
}

接口测试


$ curl -X PATCH http://127.0.0.1:8000/v1/words/1/level \
-H "Authorization: eyJhbGci...5U" \
-H "Content-Type: application/json" \
-d '{
"proficiency_level": 5
}'

{
    "code": 0,
    "message": "",
    "data": null
}