postsharelogic.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package logic
  2. import (
  3. "context"
  4. "slowwild/internal/errorx"
  5. "slowwild/internal/model"
  6. "slowwild/internal/svc"
  7. "git.banshen.xyz/huangguangrong/slow_wild_protobuff/slowwild/slowwildserver"
  8. "time"
  9. "slowwild/internal/constants"
  10. "github.com/spf13/cast"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "gorm.io/gorm"
  13. )
  14. type PostShareLogic struct {
  15. ctx context.Context
  16. svcCtx *svc.ServiceContext
  17. logx.Logger
  18. }
  19. func NewPostShareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PostShareLogic {
  20. return &PostShareLogic{
  21. ctx: ctx,
  22. svcCtx: svcCtx,
  23. Logger: logx.WithContext(ctx),
  24. }
  25. }
  26. // 分享帖子
  27. func (l *PostShareLogic) PostShare(in *slowwildserver.PostShareReq) (*slowwildserver.PostShareRsp, error) {
  28. // 从context中获取userId
  29. userId, err := cast.ToInt64E(l.ctx.Value(constants.UserIDKey))
  30. if err != nil {
  31. return nil, errorx.ErrInvalidParam
  32. }
  33. if in.PostId <= 0 {
  34. return nil, errorx.ErrInvalidParam
  35. }
  36. // 开启事务
  37. err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error {
  38. postModel := model.NewPostModel(tx, l.svcCtx.Redis)
  39. postActionModel := model.NewPostActionModel(tx, l.svcCtx.Redis)
  40. messageModel := model.NewMessageModel(tx)
  41. // 获取帖子信息
  42. post, err := postModel.GetPostDetail(l.ctx, in.PostId)
  43. if err != nil {
  44. return err
  45. }
  46. // 检查是否已经分享过
  47. isShared, err := postActionModel.CheckPostAction(l.ctx, userId, in.PostId, 2) // 2表示分享动作
  48. if err != nil {
  49. return err
  50. }
  51. if isShared {
  52. return errorx.NewCodeError(20011, "已经分享过该帖子")
  53. }
  54. // 创建分享记录
  55. postAction := &model.PostAction{
  56. Model: &model.Model{
  57. CreatedOn: time.Now().Unix(),
  58. ModifiedOn: time.Now().Unix(),
  59. },
  60. PostId: in.PostId,
  61. UserId: userId,
  62. ActionType: 2, // 2表示分享
  63. }
  64. if err := postActionModel.CreatePostAction(l.ctx, postAction); err != nil {
  65. return err
  66. }
  67. // 增加分享数
  68. if err := postModel.IncrementShareCount(l.ctx, in.PostId); err != nil {
  69. return err
  70. }
  71. // 如果不是分享自己的帖子,发送消息通知
  72. if post.UserId != userId {
  73. err = messageModel.SendNotification(l.ctx, userId, post.UserId, 5,
  74. "分享通知",
  75. "有人分享了你的动态",
  76. in.PostId, 0, 0)
  77. if err != nil {
  78. return err
  79. }
  80. }
  81. return nil
  82. })
  83. if err != nil {
  84. l.Logger.Errorf("分享帖子失败: %v", err)
  85. return nil, err
  86. }
  87. return &slowwildserver.PostShareRsp{}, nil
  88. }