fix(social): 关注与取关改为幂等写入

SocialRepository.Follow 和 Unfollow 返回本次是否真的写入。判重交给唯一索引 idx_social_follower_vlogger。

因此重复关注和重复取关返回 200。重复请求不再落成 500。

缓存失效与通知只在真的变更时发生。自关注返回 400。响应体新增 created 与 deleted 字段。

SocialWorker 的调用只适配新签名,职责不变。删除它由后续提交完成。

验证:go build ./... 通过,go test -count=1 ./internal/social/... ./internal/worker/... 全绿。
This commit is contained in:
2026-11-11 16:18:49 +08:00
parent c73c8861db
commit f658b7e76e
7 changed files with 463 additions and 71 deletions

View File

@@ -5,6 +5,7 @@ import (
"feedsystem_video_go/internal/account"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type SocialRepository struct {
@@ -15,14 +16,27 @@ func NewSocialRepository(db *gorm.DB) *SocialRepository {
return &SocialRepository{db: db}
}
func (r *SocialRepository) Follow(ctx context.Context, social *Social) error {
return r.db.WithContext(ctx).Create(social).Error
// Follow 返回本次是否真的插入关系:重复关注是幂等成功,不是错误。
// 判重交给唯一索引 idx_social_follower_vlogger,OnConflict 把冲突变成一次不报错的 SQL。
func (r *SocialRepository) Follow(ctx context.Context, social *Social) (bool, error) {
res := r.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).
Create(social)
if res.Error != nil {
return false, res.Error
}
return res.RowsAffected > 0, nil
}
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) error {
return r.db.WithContext(ctx).
// Unfollow 用影响行数回答"这次是否真的删掉":第二次取关是空操作。
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) (bool, error) {
res := r.db.WithContext(ctx).
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
Delete(&Social{}).Error
Delete(&Social{})
if res.Error != nil {
return false, res.Error
}
return res.RowsAffected > 0, nil
}
func (r *SocialRepository) GetAllFollowers(ctx context.Context, VloggerID uint) ([]*account.Account, error) {