编辑单词使用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;
id | uid | word | definition | example_sentence | chinese_translation | pronunciation | proficiency_level | created_at | updated_at |
---|---|---|---|---|---|---|---|---|---|
1 | 1 | example_update | A representative form or pattern. | This is an example sentence. | 例子 | ɪɡˈzɑːmp(ə)l | 3 | 2024/11/12 15:38:50 | 2024/11/12 15:38:50 |