feat(post): implement share recording functionality
- Added RecordShare method in PostHandler to handle sharing posts and increment share count. - Introduced IncrementShares method in PostRepository to update shares_count for published posts. - Updated PostService to include RecordShare, ensuring cache invalidation for post details and lists. - Integrated new share route in the router for handling share requests.
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"carrot_bbs/internal/dto"
|
||||
"carrot_bbs/internal/model"
|
||||
@@ -145,6 +146,41 @@ func (h *PostHandler) RecordView(c *gin.Context) {
|
||||
response.Success(c, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// RecordShare 记录帖子分享(shares_count +1,仅已发布)
|
||||
// 支持可选 JSON:{"channel":"wechat"|"qq"|"copy_link"|"system"|...},用于后续统计
|
||||
func (h *PostHandler) RecordShare(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
_ = c.GetString("user_id") // 预留:登录用户维度统计
|
||||
|
||||
type shareBody struct {
|
||||
Channel string `json:"channel"`
|
||||
}
|
||||
var body shareBody
|
||||
if c.Request.ContentLength > 0 {
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.BadRequest(c, "invalid json body")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
sharesCount, err := h.postService.RecordShare(c.Request.Context(), id, c.GetString("user_id"))
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.NotFound(c, "post not found")
|
||||
return
|
||||
}
|
||||
fmt.Printf("[ERROR] RecordShare post %s: %v\n", id, err)
|
||||
response.InternalServerError(c, "failed to record share")
|
||||
return
|
||||
}
|
||||
|
||||
data := gin.H{"success": true, "shares_count": sharesCount}
|
||||
if body.Channel != "" {
|
||||
data["channel"] = body.Channel
|
||||
}
|
||||
response.Success(c, data)
|
||||
}
|
||||
|
||||
// List 获取帖子列表(支持游标分页和偏移分页)
|
||||
func (h *PostHandler) List(c *gin.Context) {
|
||||
// 检查是否使用游标分页
|
||||
|
||||
Reference in New Issue
Block a user