Skip to content

Commit

Permalink
feat(controllers/comments.RecentCommentByPage): init
Browse files Browse the repository at this point in the history
  • Loading branch information
Prince213 committed Apr 26, 2024
1 parent 2a3fc6f commit fdf8fb7
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions internal/controllers/comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package controllers

import (
"coursebench-backend/internal/controllers/comments"

"github.com/gofiber/fiber/v2"
)

Expand All @@ -14,6 +15,7 @@ func CommentRoutes(r fiber.Router) {
route.Get("/course_group/:id", comments.CourseGroupComment)
route.Get("/course/:id", comments.CourseComment)
route.Get("/recent", comments.RecentComment)
route.Get("/recent/:id", comments.RecentCommentByPage)
route.Post("/like", comments.Like)
route.Post("/fold", comments.Fold)
route.Post("/cover", comments.Cover)
Expand Down
52 changes: 52 additions & 0 deletions internal/controllers/comments/recent_by_page.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package comments

import (
"coursebench-backend/internal/middlewares/session"
"coursebench-backend/internal/utils"
"coursebench-backend/pkg/database"
"coursebench-backend/pkg/errors"
"coursebench-backend/pkg/models"
"strconv"

"github.com/gofiber/fiber/v2"
)

func RecentCommentByPage(c *fiber.Ctx) (err error) {
uid, err := session.GetUserID(c)
if err != nil {
uid = 0
}

id_s := c.Params("id", "1")
id, err := strconv.Atoi(id_s)
if err != nil {
return errors.New(errors.InvalidArgument)
}

db := database.GetDB()
var comments []models.Comment
result := db.Preload("User").Preload("CourseGroup").Preload("CourseGroup.Course").Preload("CourseGroup.Teachers").
Order("update_time DESC").Offset((id - 1) * 30).Limit(31).Find(&comments)
if err := result.Error; err != nil {
return errors.Wrap(err, errors.DatabaseError)
}
if result.RowsAffected == 31 {
comments = comments[:30]
}

var likeResult []CommentLikeResult
if uid != 0 {
db.Raw("SELECT comment_likes.comment_id, comment_likes.is_like from comments, comment_likes where comment_likes.user_id = ? and comment_likes.comment_id = comments.id and comment_likes.deleted_at is NULL and comments.deleted_at is NULL order by create_time desc OFFSET ? LIMIT 30",
(id-1)*30,
uid).Scan(&likeResult)
}
var response []CommentResponse
response = GenerateResponse(comments, uid, likeResult, true, utils.GetIP(c))
return c.Status(fiber.StatusOK).JSON(models.OKResponse{
Data: fiber.Map{
"has_more": result.RowsAffected == 31,
"comments": response,
},
Error: false,
})
}

0 comments on commit fdf8fb7

Please sign in to comment.