/
like.go
60 lines (52 loc) · 1.5 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
package model
import (
"context"
"time"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
type Like struct {
ID uint `json:"id"`
CreatedAt time.Time `json:"createdAt"`
ArtID uint `gorm:"uniqueIndex:user_card_uq" json:"-"`
Art Art `json:"-"`
UserID uint `gorm:"uniqueIndex:user_card_uq" json:"-"`
}
type LikePile struct {
db *gorm.DB
}
func NewLikePile(db *gorm.DB) *LikePile {
return &LikePile{db: db}
}
func (lp *LikePile) Get(ctx context.Context, userID uint, artID uint) (Like, error) {
var like Like
err := lp.db.WithContext(ctx).Where("user_id = ? and art_id = ?", userID, artID).Limit(1).First(&like).Error
return like, err
}
func (lp *LikePile) GetList(ctx context.Context, userID uint) ([]Like, error) {
var likes []Like
err := lp.db.WithContext(ctx).Where("user_id = ?", userID).Find(&likes).Error
return likes, err
}
func (lp *LikePile) Set(ctx context.Context, userID uint, artID uint, liked bool) error {
var like Like
if !liked {
result := lp.db.WithContext(ctx).Where("user_id = ?", userID).Where("art_id = ?", artID).Delete(&like)
if err := result.Error; err != nil {
return err
}
if result.RowsAffected > 0 {
log.Info().Msgf("[like_pile] УДАЛЁН ЛАЙК u=%d art=%d", userID, artID)
} else {
log.Info().Msgf("[like_pile] ЛАЙК НЕ БЫЛ УСТАНОВЛЕН, u=%d art=%d", userID, artID)
}
return nil
} else {
like = Like{
ArtID: artID,
UserID: userID,
}
err := lp.db.Create(&like).Error
return err
}
}