| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- package controller
- import (
- "errors"
- "net/http"
- "woord-core-service/model"
- "github.com/gin-gonic/gin"
- "gorm.io/gorm"
- )
- type ListDictsResponse struct {
- Total uint `json:"total"`
- List []model.DictResult `json:"list"`
- }
- // 列出所有词库
- func ListDicts(c *gin.Context) {
- dicts, err := model.ListDicts(&model.Dict{
- UserID: c.MustGet(AuthUserKey).(uint),
- })
- if err != nil {
- respondUnknownError(c, err)
- return
- }
- respondOK(c, &ListDictsResponse{
- Total: uint(len(dicts)),
- List: dicts,
- })
- }
- type GetDictRequest struct {
- DictID uint `form:"id" binding:"required"`
- }
- type GetDictResponse struct {
- *model.DictResult `json:"dict"`
- Words ListWordsResponse `json:"words"`
- }
- // 获取词库
- func GetDict(c *gin.Context) {
- var request GetDictRequest
- if err := c.ShouldBind(&request); err != nil {
- respondError(c, http.StatusBadRequest, err)
- return
- }
- dict, err := model.GetDict(&model.Dict{
- Model: &gorm.Model{
- ID: request.DictID,
- },
- UserID: c.MustGet(AuthUserKey).(uint),
- })
- if err != nil {
- if errors.Is(err, model.ErrDictNotFound) {
- respondError(c, http.StatusNotFound, err)
- } else {
- respondUnknownError(c, err)
- }
- return
- }
- words, err := model.ListWords(&model.Word{
- DictID: request.DictID,
- })
- if err != nil {
- respondUnknownError(c, err)
- return
- }
- respondOK(c, &GetDictResponse{
- DictResult: dict,
- Words: ListWordsResponse{
- Total: uint(len(words)),
- List: words,
- },
- })
- }
- type CreateDictRequest struct {
- DictName string `form:"name" binding:"required"`
- ValueTitle string `form:"value" binding:"required"`
- MeaningTitle string `form:"meaning" binding:"required"`
- ExtraTitle string `form:"extra"`
- }
- // 创建词库
- func CreateDict(c *gin.Context) {
- var request CreateDictRequest
- if err := c.ShouldBind(&request); err != nil {
- respondError(c, http.StatusBadRequest, err)
- return
- }
- dict, err := model.CreateDict(&model.Dict{
- Name: request.DictName,
- ValueTitle: request.ValueTitle,
- MeaningTitle: request.MeaningTitle,
- ExtraTitle: request.ExtraTitle,
- UserID: c.MustGet(AuthUserKey).(uint),
- })
- if err != nil {
- respondUnknownError(c, err)
- return
- }
- respondOK(c, dict)
- }
|