From 4d618a91fe2e2fb3c5da0f4859d4842a7161439b Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Tue, 6 Feb 2024 10:57:05 +0800 Subject: [PATCH] :bug: Fix get single won't get react info --- pkg/server/posts_api.go | 10 ++++++---- pkg/services/posts.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/pkg/server/posts_api.go b/pkg/server/posts_api.go index 2b4b8fc..3e228e0 100644 --- a/pkg/server/posts_api.go +++ b/pkg/server/posts_api.go @@ -53,14 +53,16 @@ func getPost(c *fiber.Ctx) error { take := c.QueryInt("take", 0) offset := c.QueryInt("offset", 0) - var post models.Post - if err := services.PreloadRelatedPost(database.C.Where(&models.Post{ + tx := database.C.Where(&models.Post{ BaseModel: models.BaseModel{ID: uint(id)}, - })).First(&post).Error; err != nil { + }) + + post, err := services.GetPost(tx) + if err != nil { return fiber.NewError(fiber.StatusNotFound, err.Error()) } - tx := database.C. + tx = database.C. Where(&models.Post{ReplyID: &post.ID}). Where("published_at <= ? OR published_at IS NULL", time.Now()). Order("created_at desc") diff --git a/pkg/services/posts.go b/pkg/services/posts.go index 065afd6..dd40cf1 100644 --- a/pkg/services/posts.go +++ b/pkg/services/posts.go @@ -30,6 +30,38 @@ func PreloadRelatedPost(tx *gorm.DB) *gorm.DB { Preload("ReplyTo.Tags") } +func GetPost(tx *gorm.DB) (*models.Post, error) { + var post *models.Post + if err := PreloadRelatedPost(tx). + First(&post).Error; err != nil { + return post, err + } + + var reactInfo struct { + PostID uint + LikeCount int64 + DislikeCount int64 + } + + prefix := viper.GetString("database.prefix") + database.C.Raw(fmt.Sprintf(`SELECT t.id as post_id, + COALESCE(l.like_count, 0) AS like_count, + COALESCE(d.dislike_count, 0) AS dislike_count +FROM %sposts t + LEFT JOIN (SELECT post_id, COUNT(*) AS like_count + FROM %spost_likes + GROUP BY post_id) l ON t.id = l.post_id + LEFT JOIN (SELECT post_id, COUNT(*) AS dislike_count + FROM %spost_dislikes + GROUP BY post_id) d ON t.id = d.post_id +WHERE t.id = ?`, prefix, prefix, prefix), post.ID).Scan(&reactInfo) + + post.LikeCount = reactInfo.LikeCount + post.DislikeCount = reactInfo.DislikeCount + + return post, nil +} + func ListPost(tx *gorm.DB, take int, offset int) ([]*models.Post, error) { var posts []*models.Post if err := PreloadRelatedPost(tx).