| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- package logic
- import (
- "context"
- "slowwild/internal/errorx"
- "slowwild/internal/model"
- "slowwild/internal/svc"
- "git.banshen.xyz/huangguangrong/slow_wild_protobuff/slowwild/slowwildserver"
- "time"
- "slowwild/internal/constants"
- "github.com/spf13/cast"
- "github.com/zeromicro/go-zero/core/logx"
- "gorm.io/gorm"
- )
- type PostShareLogic struct {
- ctx context.Context
- svcCtx *svc.ServiceContext
- logx.Logger
- }
- func NewPostShareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PostShareLogic {
- return &PostShareLogic{
- ctx: ctx,
- svcCtx: svcCtx,
- Logger: logx.WithContext(ctx),
- }
- }
- // 分享帖子
- func (l *PostShareLogic) PostShare(in *slowwildserver.PostShareReq) (*slowwildserver.PostShareRsp, error) {
- // 从context中获取userId
- userId, err := cast.ToInt64E(l.ctx.Value(constants.UserIDKey))
- if err != nil {
- return nil, errorx.ErrInvalidParam
- }
- if in.PostId <= 0 {
- return nil, errorx.ErrInvalidParam
- }
- // 开启事务
- err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error {
- postModel := model.NewPostModel(tx, l.svcCtx.Redis)
- postActionModel := model.NewPostActionModel(tx, l.svcCtx.Redis)
- messageModel := model.NewMessageModel(tx)
- // 获取帖子信息
- post, err := postModel.GetPostDetail(l.ctx, in.PostId)
- if err != nil {
- return err
- }
- // 检查是否已经分享过
- isShared, err := postActionModel.CheckPostAction(l.ctx, userId, in.PostId, 2) // 2表示分享动作
- if err != nil {
- return err
- }
- if isShared {
- return errorx.NewCodeError(20011, "已经分享过该帖子")
- }
- // 创建分享记录
- postAction := &model.PostAction{
- Model: &model.Model{
- CreatedOn: time.Now().Unix(),
- ModifiedOn: time.Now().Unix(),
- },
- PostId: in.PostId,
- UserId: userId,
- ActionType: 2, // 2表示分享
- }
- if err := postActionModel.CreatePostAction(l.ctx, postAction); err != nil {
- return err
- }
- // 增加分享数
- if err := postModel.IncrementShareCount(l.ctx, in.PostId); err != nil {
- return err
- }
- // 如果不是分享自己的帖子,发送消息通知
- if post.UserId != userId {
- err = messageModel.SendNotification(l.ctx, userId, post.UserId, 5,
- "分享通知",
- "有人分享了你的动态",
- in.PostId, 0, 0)
- if err != nil {
- return err
- }
- }
- return nil
- })
- if err != nil {
- l.Logger.Errorf("分享帖子失败: %v", err)
- return nil, err
- }
- return &slowwildserver.PostShareRsp{}, nil
- }
|