diff --git a/internal/controllers/comments.go b/internal/controllers/comments.go index d8c8dd0..1d523d0 100644 --- a/internal/controllers/comments.go +++ b/internal/controllers/comments.go @@ -2,6 +2,7 @@ package controllers import ( "coursebench-backend/internal/controllers/comments" + "github.com/gofiber/fiber/v2" ) @@ -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) diff --git a/internal/controllers/comments/recent_by_page.go b/internal/controllers/comments/recent_by_page.go new file mode 100644 index 0000000..041483c --- /dev/null +++ b/internal/controllers/comments/recent_by_page.go @@ -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, + }) +}