🐛 Fix batch list reactions cannot work properly

This commit is contained in:
LittleSheep 2024-07-05 21:06:18 +08:00
parent d7113b5237
commit 0015952f92
5 changed files with 17 additions and 13 deletions

View File

@ -61,7 +61,8 @@ func listArticle(c *fiber.Ctx) error {
tx = services.FilterArticleWithTag(tx, c.Query("tag"))
}
count, err := services.CountArticle(tx)
counTx := tx
count, err := services.CountArticle(counTx)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}

View File

@ -62,7 +62,8 @@ func listPost(c *fiber.Ctx) error {
tx = services.FilterPostWithTag(tx, c.Query("tag"))
}
count, err := services.CountPost(tx)
countTx := tx
count, err := services.CountPost(countTx)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}

View File

@ -121,7 +121,7 @@ func ListArticle(tx *gorm.DB, take int, offset int, noReact ...bool) ([]*models.
// Load reactions
if len(noReact) <= 0 || !noReact[0] {
if mapping, err := BatchListResourceReactions(database.C.Where("article_id IN ?", idx)); err != nil {
if mapping, err := BatchListResourceReactions(database.C.Where("article_id IN ?", idx), "article_id"); err != nil {
return items, err
} else {
itemMap := lo.SliceToMap(items, func(item *models.Article) (uint, *models.Article) {

View File

@ -152,7 +152,7 @@ func ListPost(tx *gorm.DB, take int, offset int, noReact ...bool) ([]*models.Pos
// Load reactions
if len(noReact) <= 0 || !noReact[0] {
if mapping, err := BatchListResourceReactions(database.C.Where("post_id IN ?", idx)); err != nil {
if mapping, err := BatchListResourceReactions(database.C.Where("post_id IN ?", idx), "post_id"); err != nil {
return items, err
} else {
itemMap := lo.SliceToMap(items, func(item *models.Post) (uint, *models.Post) {

View File

@ -1,6 +1,8 @@
package services
import (
"fmt"
"git.solsynth.dev/hydrogen/interactive/pkg/internal/models"
"github.com/samber/lo"
"gorm.io/gorm"
@ -28,26 +30,26 @@ func ListResourceReactions(tx *gorm.DB) (map[string]int64, error) {
}), nil
}
func BatchListResourceReactions(tx *gorm.DB) (map[uint]map[string]int64, error) {
func BatchListResourceReactions(tx *gorm.DB, indexField string) (map[uint]map[string]int64, error) {
var reactions []struct {
ArticleID uint
Symbol string
Count int64
ID uint
Symbol string
Count int64
}
reactInfo := map[uint]map[string]int64{}
if err := tx.Model(&models.Reaction{}).
Select("article_id, symbol, COUNT(id) as count").
Group("article_id, symbol").
Select(fmt.Sprintf("%s as id, symbol, COUNT(id) as count"), indexField).
Group("id, symbol").
Scan(&reactions).Error; err != nil {
return reactInfo, err
}
for _, info := range reactions {
if _, ok := reactInfo[info.ArticleID]; !ok {
reactInfo[info.ArticleID] = make(map[string]int64)
if _, ok := reactInfo[info.ID]; !ok {
reactInfo[info.ID] = make(map[string]int64)
}
reactInfo[info.ArticleID][info.Symbol] = info.Count
reactInfo[info.ID][info.Symbol] = info.Count
}
return reactInfo, nil