postsharelogic.go 2.2 KB

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