topics_controller.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package v1
  2. import (
  3. "github.com/runningwater/gohub/app/models/topic"
  4. "github.com/runningwater/gohub/app/policies"
  5. "github.com/runningwater/gohub/app/requests"
  6. "github.com/runningwater/gohub/pkg/auth"
  7. "github.com/runningwater/gohub/pkg/response"
  8. "github.com/gin-gonic/gin"
  9. )
  10. type TopicsController struct {
  11. BaseApiController
  12. }
  13. func (ctrl *TopicsController) Show(c *gin.Context) {
  14. topicModel := topic.Get(c.Param("id"))
  15. if topicModel.ID == 0 {
  16. response.Abort404(c)
  17. return
  18. }
  19. response.Data(c, topicModel)
  20. }
  21. func (ctrl *TopicsController) Index(c *gin.Context) {
  22. request := requests.PaginationRequest{}
  23. if ok := requests.Validate(c, &request, requests.Pagination); !ok {
  24. return
  25. }
  26. data, pager := topic.Paginate(c, 10)
  27. response.JSON(c, gin.H{
  28. "data": data,
  29. "pager": pager,
  30. })
  31. }
  32. func (ctrl *TopicsController) Store(c *gin.Context) {
  33. request := requests.TopicRequest{}
  34. if ok := requests.Validate(c, &request, requests.TopicSave); !ok {
  35. return
  36. }
  37. topicModel := topic.Topic{
  38. Title: request.Title,
  39. Body: request.Body,
  40. CategoryID: request.CategoryID,
  41. UserID: auth.CurrentUID(c),
  42. }
  43. topicModel.Create()
  44. if topicModel.ID > 0 {
  45. response.Created(c, topicModel)
  46. } else {
  47. response.Abort500(c, "创建失败,请稍后尝试~")
  48. }
  49. }
  50. func (ctrl *TopicsController) Update(c *gin.Context) {
  51. topicModel := topic.Get(c.Param("id"))
  52. if topicModel.ID == 0 {
  53. response.Abort404(c)
  54. return
  55. }
  56. request := requests.TopicRequest{}
  57. if ok := requests.Validate(c, &request, requests.TopicSave); !ok {
  58. return
  59. }
  60. if !policies.CanModifyTopic(c, topicModel) {
  61. response.Abort403(c)
  62. return
  63. }
  64. topicModel.Title = request.Title
  65. topicModel.Body = request.Body
  66. topicModel.CategoryID = request.CategoryID
  67. rowsAffected := topicModel.Save()
  68. if rowsAffected > 0 {
  69. response.Data(c, topicModel)
  70. } else {
  71. response.Abort500(c, "更新失败,请稍后尝试~")
  72. }
  73. }
  74. func (ctrl *TopicsController) Delete(c *gin.Context) {
  75. topicModel := topic.Get(c.Param("id"))
  76. if topicModel.ID == 0 {
  77. response.Abort404(c)
  78. return
  79. }
  80. if !policies.CanModifyTopic(c, topicModel) {
  81. response.Abort403(c)
  82. return
  83. }
  84. rowsAffected := topicModel.Delete()
  85. if rowsAffected > 0 {
  86. response.Success(c)
  87. return
  88. }
  89. response.Abort500(c, "删除失败,请稍后尝试~")
  90. }