fix: Service 层移除直接持有的 *gorm.DB,引入 Repository Transaction 方法
- ReactionStore/FollowStore/EnergyStore/FavoriteStore 接口新增 Transaction 方法 - EnergyStore.Transaction 支持跨仓库事务(EnergyStore + FundStore) - ReactionRepo/FollowRepo/FavoriteRepo/EnergyRepo 实现 Transaction 方法 - ReactionRepo 新增 GetPostLikesCount 方法,消除 Service 直查 DB - ReactionService/FollowService/FavoriteService/EnergyService 移除 db 字段 - EnergyRepo 通过 SetFundStore 注入 FundStore 用于跨仓库事务 - 更新 deps_extra.go 构造函数调用
This commit is contained in:
@ -4,10 +4,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ReactionType 反应类型
|
||||
@ -21,13 +18,12 @@ const (
|
||||
|
||||
// ReactionService 赞/踩业务逻辑
|
||||
type ReactionService struct {
|
||||
db *gorm.DB
|
||||
repo ReactionStore
|
||||
}
|
||||
|
||||
// NewReactionService 构造函数
|
||||
func NewReactionService(db *gorm.DB, repo ReactionStore) *ReactionService {
|
||||
return &ReactionService{db: db, repo: repo}
|
||||
func NewReactionService(repo ReactionStore) *ReactionService {
|
||||
return &ReactionService{repo: repo}
|
||||
}
|
||||
|
||||
// ToggleLike 切换点赞(含踩互斥逻辑)
|
||||
@ -35,9 +31,7 @@ func NewReactionService(db *gorm.DB, repo ReactionStore) *ReactionService {
|
||||
func (s *ReactionService) ToggleLike(userID, postID uint) (bool, error) {
|
||||
var isLiked bool
|
||||
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
txRepo := s.repo.WithTx(tx)
|
||||
|
||||
err := s.repo.Transaction(func(txRepo ReactionStore) error {
|
||||
// 查当前状态
|
||||
_, likeErr := txRepo.FindLike(userID, postID)
|
||||
hasLike := likeErr == nil
|
||||
@ -104,9 +98,7 @@ func (s *ReactionService) recordLikeForAggregation(postID uint, likerID uint) {
|
||||
func (s *ReactionService) ToggleDislike(userID, postID uint) (bool, error) {
|
||||
var isDisliked bool
|
||||
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
txRepo := s.repo.WithTx(tx)
|
||||
|
||||
err := s.repo.Transaction(func(txRepo ReactionStore) error {
|
||||
// 查当前状态
|
||||
_, likeErr := txRepo.FindLike(userID, postID)
|
||||
hasLike := likeErr == nil
|
||||
@ -165,12 +157,9 @@ func (s *ReactionService) GetReaction(userID, postID uint) (ReactionType, error)
|
||||
|
||||
// GetPostLikesCount 查询文章点赞数(公开展示)
|
||||
func (s *ReactionService) GetPostLikesCount(postID uint) (int, error) {
|
||||
var post model.Post
|
||||
if err := s.db.Select("likes_count").First(&post, postID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return 0, common.ErrPostNotFound
|
||||
}
|
||||
return 0, fmt.Errorf("查询文章失败: %w", err)
|
||||
count, err := s.repo.GetPostLikesCount(postID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("查询文章点赞数: %w", err)
|
||||
}
|
||||
return post.LikesCount, nil
|
||||
return count, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user