userfollowlogic.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package logic
  2. import (
  3. "context"
  4. "slowwild/internal/svc"
  5. "git.banshen.xyz/huangguangrong/slow_wild_protobuff/slowwild/slowwildserver"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. "gorm.io/gorm"
  8. "slowwild/internal/errorx"
  9. "slowwild/internal/model"
  10. )
  11. type UserFollowLogic struct {
  12. ctx context.Context
  13. svcCtx *svc.ServiceContext
  14. logx.Logger
  15. }
  16. func NewUserFollowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFollowLogic {
  17. return &UserFollowLogic{
  18. ctx: ctx,
  19. svcCtx: svcCtx,
  20. Logger: logx.WithContext(ctx),
  21. }
  22. }
  23. // 关注用户
  24. func (l *UserFollowLogic) UserFollow(in *slowwildserver.FollowUserReq) (*slowwildserver.FollowUserRes, error) {
  25. if in.UserId <= 0 || in.FollowUserId <= 0 {
  26. return nil, errorx.ErrInvalidParam
  27. }
  28. // 检查是否已经关注
  29. followMap, err := l.svcCtx.UserFollowModel.CheckMutualFollows(l.ctx, in.UserId, []int64{in.FollowUserId})
  30. if err != nil {
  31. return nil, errorx.ErrUserQueryFailed
  32. }
  33. if followMap[in.FollowUserId] {
  34. return nil, errorx.NewCodeError(10010, "已经关注该用户")
  35. }
  36. // 开启事务
  37. err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error {
  38. userModel := model.NewUserModel(tx)
  39. userFollowModel := model.NewUserFollowModel(tx)
  40. // 创建关注关系
  41. err := userFollowModel.Follow(l.ctx, in.UserId, in.FollowUserId)
  42. if err != nil {
  43. return err
  44. }
  45. // 增加当前用户的关注数
  46. err = userModel.IncrementFollowCount(l.ctx, in.UserId)
  47. if err != nil {
  48. return err
  49. }
  50. // 增加目标用户的粉丝数
  51. err = userModel.IncrementFansCount(l.ctx, in.FollowUserId)
  52. if err != nil {
  53. return err
  54. }
  55. return nil
  56. })
  57. if err != nil {
  58. l.Logger.Errorf("关注用户失败: %v", err)
  59. return nil, errorx.NewCodeError(10011, "关注用户失败")
  60. }
  61. return &slowwildserver.FollowUserRes{}, nil
  62. }