dicts.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package controller
  2. import (
  3. "errors"
  4. "net/http"
  5. "woord-core-service/model"
  6. "github.com/gin-gonic/gin"
  7. "gorm.io/gorm"
  8. )
  9. type ListDictsResponse struct {
  10. Total uint `json:"total"`
  11. List []model.DictResult `json:"list"`
  12. }
  13. // 列出所有词库
  14. func ListDicts(c *gin.Context) {
  15. dicts, err := model.ListDicts(&model.Dict{
  16. UserID: c.MustGet(AuthUserKey).(uint),
  17. })
  18. if err != nil {
  19. respondUnknownError(c, err)
  20. return
  21. }
  22. respondOK(c, &ListDictsResponse{
  23. Total: uint(len(dicts)),
  24. List: dicts,
  25. })
  26. }
  27. type GetDictRequest struct {
  28. DictID uint `form:"id" binding:"required"`
  29. }
  30. type GetDictResponse struct {
  31. *model.DictResult `json:"dict"`
  32. Words ListWordsResponse `json:"words"`
  33. }
  34. // 获取词库
  35. func GetDict(c *gin.Context) {
  36. var request GetDictRequest
  37. if err := c.ShouldBind(&request); err != nil {
  38. respondError(c, http.StatusBadRequest, err)
  39. return
  40. }
  41. dict, err := model.GetDict(&model.Dict{
  42. Model: &gorm.Model{
  43. ID: request.DictID,
  44. },
  45. UserID: c.MustGet(AuthUserKey).(uint),
  46. })
  47. if err != nil {
  48. if errors.Is(err, model.ErrDictNotFound) {
  49. respondError(c, http.StatusNotFound, err)
  50. } else {
  51. respondUnknownError(c, err)
  52. }
  53. return
  54. }
  55. words, err := model.ListWords(&model.Word{
  56. DictID: request.DictID,
  57. })
  58. if err != nil {
  59. respondUnknownError(c, err)
  60. return
  61. }
  62. respondOK(c, &GetDictResponse{
  63. DictResult: dict,
  64. Words: ListWordsResponse{
  65. Total: uint(len(words)),
  66. List: words,
  67. },
  68. })
  69. }
  70. type CreateDictRequest struct {
  71. DictName string `form:"name" binding:"required"`
  72. ValueTitle string `form:"value" binding:"required"`
  73. MeaningTitle string `form:"meaning" binding:"required"`
  74. ExtraTitle string `form:"extra"`
  75. }
  76. // 创建词库
  77. func CreateDict(c *gin.Context) {
  78. var request CreateDictRequest
  79. if err := c.ShouldBind(&request); err != nil {
  80. respondError(c, http.StatusBadRequest, err)
  81. return
  82. }
  83. dict, err := model.CreateDict(&model.Dict{
  84. Name: request.DictName,
  85. ValueTitle: request.ValueTitle,
  86. MeaningTitle: request.MeaningTitle,
  87. ExtraTitle: request.ExtraTitle,
  88. UserID: c.MustGet(AuthUserKey).(uint),
  89. })
  90. if err != nil {
  91. respondUnknownError(c, err)
  92. return
  93. }
  94. respondOK(c, dict)
  95. }