跳到主要内容
版本:2.8.x(Latest)

编辑单词使用PUT方式,代表更新资源。

添加 Api


api/words/v1/words.go

type UpdateReq struct {  
g.Meta `path:"words/{id}" method:"put" sm:"更新" tags:"单词"`
Id uint `json:"id" v:"required"`
Word string `json:"word" v:"required|length:1,100" dc:"单词"`
Definition string `json:"definition" v:"required|length:1,300" dc:"单词定义"`
ExampleSentence string `json:"example_sentence" v:"required|length:1,300" dc:"例句"`
ChineseTranslation string `json:"chinese_translation" v:"required|length:1,300" dc:"中文翻译"`
Pronunciation string `json:"pronunciation" v:"required|length:1,100" dc:"发音"`
ProficiencyLevel ProficiencyLevel `json:"proficiency_level" v:"required|between:1,5" dc:"熟练度,1最低,5最高"`
}

type UpdateRes struct {
}

编写Logic


internal/logic/words/words.go

package words  

...

type UpdateInput struct {
Uid uint
Word string
Definition string
ExampleSentence string
ChineseTranslation string
Pronunciation string
ProficiencyLevel v1.ProficiencyLevel
}

func (w *Words) Update(ctx context.Context, id uint, in UpdateInput) error {
var cls = dao.Words.Columns()

count, err := dao.Words.Ctx(ctx).
Where(cls.Uid, in.Uid).
Where(cls.Word, in.Word).
WhereNot(cls.Id, id).
Count()
if err != nil {
return err
}
if count > 0 {
return gerror.New("单词已存在")
}

_, err = dao.Words.Ctx(ctx).Data(do.Words{
Word: in.Word,
Definition: in.Definition,
ExampleSentence: in.ExampleSentence,
ChineseTranslation: in.ChineseTranslation,
Pronunciation: in.Pronunciation,
ProficiencyLevel: in.ProficiencyLevel,
}).Where(cls.Id, id).Where(cls.Uid, in.Uid).Update()
if err != nil {
return err
}
return nil
}

...

必须在ORM链式中加上Uid判断条件,以防止越权,后续的查询,删除动作同样如此。另外加上WhereNot,以忽略自身的单词重复检测。

Controller调用Logic


internal/controller/words/words_v1_update.go

package words  

import (
"context"

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

func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
err = c.words.Update(ctx, req.Id, words.UpdateInput{
Word: req.Word,
Definition: req.Definition,
ExampleSentence: req.ExampleSentence,
ChineseTranslation: req.ChineseTranslation,
Pronunciation: req.Pronunciation,
ProficiencyLevel: req.ProficiencyLevel,
})
return nil, err
}

接口测试


$ curl -X PUT http://127.0.0.1:8000/v1/words/1 \
-H "Authorization: eyJhbGci...5U" \
-H "Content-Type: application/json" \
-d '{
"word": "example_update",
"definition": "A representative form or pattern.",
"example_sentence": "This is an example sentence.",
"chinese_translation": "例子",
"pronunciation": "ɪɡˈzɑːmp(ə)l",
"proficiency_level": 3
}'

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

执行命令,查询数据是否正常更新:

$ SELECT * FROM words;
iduidworddefinitionexample_sentencechinese_translationpronunciationproficiency_levelcreated_atupdated_at
11example_updateA representative form or pattern.This is an example sentence.例子ɪɡˈzɑːmp(ə)l32024/11/12 15:38:502024/11/12 15:38:50