create and list comment

This commit is contained in:
cyp0633 2022-06-02 15:53:30 +08:00
parent e12c0aedd7
commit 59eaaf5eda
Signed by: cyp0633
GPG Key ID: E1BC508A994A5138
4 changed files with 81 additions and 1 deletions

View File

@ -1,12 +1,22 @@
package routers
import (
"GodPress/services/comments"
"github.com/gin-gonic/gin"
"net/http"
)
func ListComments(c *gin.Context) {
c.AbortWithStatus(http.StatusNotImplemented)
var s comments.ListCommentsService
if err := c.Bind(&s); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": -1,
"msg": err.Error(),
})
c.Abort()
return
}
s.ListComment(c)
}
func CreateComment(c *gin.Context) {

View File

@ -0,0 +1,35 @@
package comments
import (
"GodPress/models"
"GodPress/prjutil"
"github.com/gin-gonic/gin"
"net/http"
)
type CreateCommentService struct {
ArticleId uint `json:"article_id"`
Content string `json:"content"`
}
func (s *CreateCommentService) CreateComment(c *gin.Context) {
author := prjutil.GetUserFromHeader(c)
result := models.DB.Create(&models.Wp_comment{
ArticleId: s.ArticleId,
Content: s.Content,
Author: author,
})
if result.Error != nil {
prjutil.ErrorLogger.Println("create comment error:", result.Error.Error())
c.JSON(http.StatusInternalServerError, gin.H{
"code": 0,
"message": result.Error.Error(),
})
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"message": "已创建",
})
}

34
services/comments/list.go Normal file
View File

@ -0,0 +1,34 @@
package comments
import (
"GodPress/models"
"GodPress/prjutil"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"net/http"
)
type ListCommentsService struct {
PerPage uint `form:"per_page"`
}
func (s *ListCommentsService) ListComment(c *gin.Context) {
if s.PerPage == 0 {
s.PerPage = 10
}
var commentList []uint
result := models.DB.Model(models.Wp_comment{}).Select("id").Order("id desc").Limit(int(s.PerPage)).Pluck("comment_ID", &commentList)
if result.Error != nil && result.Error != gorm.ErrRecordNotFound {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 0,
"message": result.Error.Error(),
})
prjutil.ErrorLogger.Println("List comments failed", result.Error)
c.Abort()
return
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"data": commentList,
})
}

View File

@ -25,6 +25,7 @@ func (s *CreatePostService) CreatePost(c *gin.Context) {
LikeNum: 0,
})
if result.Error != nil {
prjutil.ErrorLogger.Println("create post error:", result.Error.Error())
c.JSON(http.StatusInternalServerError, gin.H{
"code": 0,
"message": result.Error.Error(),