/
like.go
118 lines (96 loc) · 2.79 KB
/
like.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package frontend
import (
"context"
"errors"
"fmt"
"time"
"github.com/gin-gonic/gin"
"github.com/hhandhuan/ku-bbs/internal/consts"
"github.com/hhandhuan/ku-bbs/internal/entity/frontend"
"github.com/hhandhuan/ku-bbs/internal/model"
"github.com/hhandhuan/ku-bbs/internal/service"
remindSub "github.com/hhandhuan/ku-bbs/internal/subject/remind"
"github.com/hhandhuan/ku-bbs/pkg/logger"
"github.com/hhandhuan/ku-bbs/pkg/mysql"
"github.com/hhandhuan/ku-bbs/pkg/redis"
"gorm.io/gorm"
)
func LikeService(ctx *gin.Context) *SLike {
return &SLike{ctx: service.Context(ctx)}
}
type SLike struct {
ctx *service.BaseContext
}
// Like 点赞提交
func (s *SLike) Like(req *frontend.LikeReq) error {
auth := s.ctx.Auth()
lockKey := fmt.Sprintf("user:%d:source:%d:like", auth.ID, req.SourceID)
val, err := redis.GetInstance().SetNX(context.Background(), lockKey, 1, time.Second*10).Result()
if err != nil {
logger.GetInstance().Error().Msgf("set setnx error: %v", err)
return errors.New("点赞失败,请稍后在试")
}
if !val {
return errors.New("点赞失败, 操作太频繁")
}
defer redis.GetInstance().Del(context.Background(), lockKey)
liked, err := s.IsLiked(req.SourceID, req.SourceType)
if err != nil {
return errors.New("点赞失败,请稍后在试")
}
if liked {
return errors.New("无法重复点赞")
}
err = mysql.GetInstance().Transaction(func(tx *gorm.DB) error {
c := tx.Create(&model.Likes{
UserId: s.ctx.Auth().ID,
SourceType: req.SourceType,
SourceId: req.SourceID,
TargetUserId: req.TargetUserID,
State: consts.Liked,
})
if c.Error != nil || c.RowsAffected <= 0 {
return errors.New("点赞失败,请稍后在试")
}
data := map[string]interface{}{
"like_count": gorm.Expr("like_count + ?", 1),
}
switch req.SourceType {
case consts.TopicSource:
u := tx.Model(&model.Topics{}).Where("id", req.SourceID).Updates(data)
if u.Error != nil || u.RowsAffected <= 0 {
return errors.New("点赞失败,请稍后在试")
}
default:
u := tx.Model(&model.Comments{}).Where("id", req.SourceID).Updates(data)
if u.Error != nil || u.RowsAffected <= 0 {
return errors.New("点赞失败,请稍后在试")
}
}
return nil
})
if err != nil {
return err
}
obs := &remindSub.LikeObs{
Sender: s.ctx.Auth().ID,
Receiver: req.TargetUserID,
SourceID: req.SourceID,
SourceType: req.SourceType,
}
sub := remindSub.New()
sub.Attach(obs)
sub.Notify()
return nil
}
// IsLiked 是否点赞
func (s *SLike) IsLiked(id uint64, source string) (bool, error) {
user := s.ctx.Auth()
var like *model.Likes
f := model.Like().Where(&model.Likes{UserId: user.ID, SourceType: source, SourceId: id}).Find(&like)
if f.Error != nil {
return false, f.Error
} else {
return like.ID > 0, nil
}
}