Pagination

This commit is contained in:
2024-02-03 15:20:32 +08:00
parent 807f7cff46
commit 1f4164e72a
15 changed files with 394 additions and 226 deletions

32
pkg/services/accounts.go Normal file
View File

@ -0,0 +1,32 @@
package services
import (
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
"errors"
"gorm.io/gorm"
)
func FollowAccount(followerId, followingId uint) error {
relationship := models.AccountMembership{
FollowerID: followerId,
FollowingID: followingId,
}
return database.C.Create(&relationship).Error
}
func UnfollowAccount(followerId, followingId uint) error {
return database.C.Where(models.AccountMembership{
FollowerID: followerId,
FollowingID: followingId,
}).Delete(&models.AccountMembership{}).Error
}
func GetAccountFollowed(user models.Account, target models.Account) (models.AccountMembership, bool) {
var relationship models.AccountMembership
err := database.C.Model(&models.AccountMembership{}).
Where(&models.AccountMembership{FollowerID: user.ID, FollowingID: target.ID}).
Find(&relationship).
Error
return relationship, !errors.Is(err, gorm.ErrRecordNotFound)
}

View File

@ -4,9 +4,61 @@ import (
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
"errors"
"fmt"
"github.com/samber/lo"
"github.com/spf13/viper"
"gorm.io/gorm"
)
func ListPost(take int, offset int) ([]*models.Post, error) {
var posts []*models.Post
if err := database.C.
Where(&models.Post{RealmID: nil}).
Limit(take).
Offset(offset).
Order("created_at desc").
Preload("Author").
Find(&posts).Error; err != nil {
return posts, err
}
postIds := lo.Map(posts, func(item *models.Post, _ int) uint {
return item.ID
})
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 IN (?)`, prefix, prefix, prefix), postIds).Scan(&reactInfo)
postMap := lo.SliceToMap(posts, func(item *models.Post) (uint, *models.Post) {
return item.ID, item
})
for _, info := range reactInfo {
if post, ok := postMap[info.PostID]; ok {
post.LikeCount = info.LikeCount
post.DislikeCount = info.DislikeCount
}
}
return posts, nil
}
func NewPost(
user models.Account,
alias, title, content string,