109 lines
2.6 KiB
Go
109 lines
2.6 KiB
Go
package controller
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"metazone.cc/mce/internal/common"
|
|
"metazone.cc/mce/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ReactionController 赞/踩 API 控制器
|
|
type ReactionController struct {
|
|
reactionSvc reactionUseCase
|
|
}
|
|
|
|
// NewReactionController 构造函数
|
|
func NewReactionController(reactionSvc reactionUseCase) *ReactionController {
|
|
return &ReactionController{reactionSvc: reactionSvc}
|
|
}
|
|
|
|
// ToggleLike 切换点赞 POST /api/posts/:id/like
|
|
func (rc *ReactionController) ToggleLike(c *gin.Context) {
|
|
uid, _, ok := common.GetGinUser(c)
|
|
if !ok {
|
|
common.Error(c, http.StatusUnauthorized, "请先登录")
|
|
return
|
|
}
|
|
|
|
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
|
return
|
|
}
|
|
|
|
isLiked, err := rc.reactionSvc.ToggleLike(uid, uint(postID))
|
|
if err != nil {
|
|
common.Error(c, http.StatusInternalServerError, "操作失败")
|
|
return
|
|
}
|
|
|
|
// 获取最新点赞数
|
|
likesCount, _ := rc.reactionSvc.GetPostLikesCount(uint(postID))
|
|
|
|
common.Ok(c, gin.H{
|
|
"liked": isLiked,
|
|
"likes_count": likesCount,
|
|
})
|
|
}
|
|
|
|
// ToggleDislike 切换踩 POST /api/posts/:id/dislike
|
|
func (rc *ReactionController) ToggleDislike(c *gin.Context) {
|
|
uid, _, ok := common.GetGinUser(c)
|
|
if !ok {
|
|
common.Error(c, http.StatusUnauthorized, "请先登录")
|
|
return
|
|
}
|
|
|
|
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
|
return
|
|
}
|
|
|
|
isDisliked, err := rc.reactionSvc.ToggleDislike(uid, uint(postID))
|
|
if err != nil {
|
|
common.Error(c, http.StatusInternalServerError, "操作失败")
|
|
return
|
|
}
|
|
|
|
common.Ok(c, gin.H{
|
|
"disliked": isDisliked,
|
|
})
|
|
}
|
|
|
|
// GetReaction 查询当前用户对文章的反应状态 GET /api/posts/:id/reaction
|
|
func (rc *ReactionController) GetReaction(c *gin.Context) {
|
|
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
|
return
|
|
}
|
|
|
|
// 未登录用户返回 none + 公开计数
|
|
uid, _, ok := common.GetGinUser(c)
|
|
if !ok {
|
|
likesCount, _ := rc.reactionSvc.GetPostLikesCount(uint(postID))
|
|
common.Ok(c, gin.H{
|
|
"reaction": string(service.ReactionNone),
|
|
"likes_count": likesCount,
|
|
})
|
|
return
|
|
}
|
|
|
|
reaction, err := rc.reactionSvc.GetReaction(uid, uint(postID))
|
|
if err != nil {
|
|
common.Error(c, http.StatusInternalServerError, "查询失败")
|
|
return
|
|
}
|
|
|
|
likesCount, _ := rc.reactionSvc.GetPostLikesCount(uint(postID))
|
|
|
|
common.Ok(c, gin.H{
|
|
"reaction": string(reaction),
|
|
"likes_count": likesCount,
|
|
})
|
|
}
|