topics_controller.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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) Index(c *gin.Context) {
  14. request := requests.PaginationRequest{}
  15. if ok := requests.Validate(c, &request, requests.Pagination); !ok {
  16. return
  17. }
  18. data, pager := topic.Paginate(c, 10)
  19. response.JSON(c, gin.H{
  20. "data": data,
  21. "pager": pager,
  22. })
  23. }
  24. func (ctrl *TopicsController) Store(c *gin.Context) {
  25. request := requests.TopicRequest{}
  26. if ok := requests.Validate(c, &request, requests.TopicSave); !ok {
  27. return
  28. }
  29. topicModel := topic.Topic{
  30. Title: request.Title,
  31. Body: request.Body,
  32. CategoryID: request.CategoryID,
  33. UserID: auth.CurrentUID(c),
  34. }
  35. topicModel.Create()
  36. if topicModel.ID > 0 {
  37. response.Created(c, topicModel)
  38. } else {
  39. response.Abort500(c, "创建失败,请稍后尝试~")
  40. }
  41. }
  42. func (ctrl *TopicsController) Update(c *gin.Context) {
  43. topicModel := topic.Get(c.Param("id"))
  44. if topicModel.ID == 0 {
  45. response.Abort404(c)
  46. return
  47. }
  48. request := requests.TopicRequest{}
  49. if ok := requests.Validate(c, &request, requests.TopicSave); !ok {
  50. return
  51. }
  52. if !policies.CanModifyTopic(c, topicModel) {
  53. response.Abort403(c)
  54. return
  55. }
  56. topicModel.Title = request.Title
  57. topicModel.Body = request.Body
  58. topicModel.CategoryID = request.CategoryID
  59. rowsAffected := topicModel.Save()
  60. if rowsAffected > 0 {
  61. response.Data(c, topicModel)
  62. } else {
  63. response.Abort500(c, "更新失败,请稍后尝试~")
  64. }
  65. }
  66. func (ctrl *TopicsController) Delete(c *gin.Context) {
  67. topicModel := topic.Get(c.Param("id"))
  68. if topicModel.ID == 0 {
  69. response.Abort404(c)
  70. return
  71. }
  72. if !policies.CanModifyTopic(c, topicModel) {
  73. response.Abort403(c)
  74. return
  75. }
  76. rowsAffected := topicModel.Delete()
  77. if rowsAffected > 0 {
  78. response.Success(c)
  79. return
  80. }
  81. response.Abort500(c, "删除失败,请稍后尝试~")
  82. }