refactor: replace standard log with zap logger and optimize code patterns
- Migrate all log.Printf/log.Println calls to structured zap logging - Use cmp.Or for cleaner default value handling - Replace manual loops with slices.ContainsFunc/IndexFunc - Add batch query methods (IsLikedBatch, IsFavoritedBatch) to solve N+1 problem - Update JSON tags from omitempty to omitzero for numeric fields - Use errgroup-style wg.Go for worker goroutines - Remove duplicate casbin/v2 dependency (keeping v3) - Add plans/ to gitignore
This commit is contained in:
@@ -285,6 +285,33 @@ func (r *PostRepository) IsLiked(postID, userID string) bool {
|
||||
return count > 0
|
||||
}
|
||||
|
||||
// IsLikedBatch 批量检查是否点赞(解决 N+1 问题)
|
||||
// 返回 map[postID]bool
|
||||
func (r *PostRepository) IsLikedBatch(postIDs []string, userID string) map[string]bool {
|
||||
result := make(map[string]bool)
|
||||
if len(postIDs) == 0 || userID == "" {
|
||||
return result
|
||||
}
|
||||
|
||||
// 初始化所有 postID 为 false
|
||||
for _, postID := range postIDs {
|
||||
result[postID] = false
|
||||
}
|
||||
|
||||
// 一次性查询所有点赞记录
|
||||
var likedPostIDs []string
|
||||
r.db.Model(&model.PostLike{}).
|
||||
Where("post_id IN ? AND user_id = ?", postIDs, userID).
|
||||
Pluck("post_id", &likedPostIDs)
|
||||
|
||||
// 更新已点赞的帖子
|
||||
for _, postID := range likedPostIDs {
|
||||
result[postID] = true
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Favorite 收藏帖子
|
||||
func (r *PostRepository) Favorite(postID, userID string) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
@@ -336,6 +363,33 @@ func (r *PostRepository) IsFavorited(postID, userID string) bool {
|
||||
return count > 0
|
||||
}
|
||||
|
||||
// IsFavoritedBatch 批量检查是否收藏(解决 N+1 问题)
|
||||
// 返回 map[postID]bool
|
||||
func (r *PostRepository) IsFavoritedBatch(postIDs []string, userID string) map[string]bool {
|
||||
result := make(map[string]bool)
|
||||
if len(postIDs) == 0 || userID == "" {
|
||||
return result
|
||||
}
|
||||
|
||||
// 初始化所有 postID 为 false
|
||||
for _, postID := range postIDs {
|
||||
result[postID] = false
|
||||
}
|
||||
|
||||
// 一次性查询所有收藏记录
|
||||
var favoritedPostIDs []string
|
||||
r.db.Model(&model.Favorite{}).
|
||||
Where("post_id IN ? AND user_id = ?", postIDs, userID).
|
||||
Pluck("post_id", &favoritedPostIDs)
|
||||
|
||||
// 更新已收藏的帖子
|
||||
for _, postID := range favoritedPostIDs {
|
||||
result[postID] = true
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// IncrementViews 增加帖子观看量
|
||||
func (r *PostRepository) IncrementViews(postID string) error {
|
||||
return r.db.Model(&model.Post{}).Where("id = ?", postID).
|
||||
|
||||
Reference in New Issue
Block a user