Skip to content

Commit

Permalink
完成点赞/收藏/阅读计数功能
Browse files Browse the repository at this point in the history
  • Loading branch information
GoSimplicity committed May 28, 2024
1 parent 2a52293 commit bc18181
Show file tree
Hide file tree
Showing 13 changed files with 214 additions and 57 deletions.
Binary file modified LinkMe
Binary file not shown.
13 changes: 6 additions & 7 deletions internal/api/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"LinkMe/internal/service"
. "LinkMe/pkg/ginp"
ijwt "LinkMe/utils/jwt"

"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
Expand Down Expand Up @@ -254,15 +253,15 @@ func (ph *PostHandler) Like(ctx *gin.Context, req LikeReq) (Result, error) {

func (ph *PostHandler) Collect(ctx *gin.Context, req CollectReq) (Result, error) {
uc := ctx.MustGet("user").(ijwt.UserClaims)
if req.Collect {
if req.Collectd {
if err := ph.intSvc.Collect(ctx, ph.biz, req.PostId, req.CollectId, uc.Uid); err != nil {
ph.l.Error(PostCollectError, zap.Error(err))
return Result{}, err
} else {
if err := ph.intSvc.CancelCollect(ctx, ph.biz, req.PostId, req.CollectId, uc.Uid); err != nil {
ph.l.Error(PostCanceCollectError, zap.Error(err))
return Result{}, err
}
}
} else {
if err := ph.intSvc.CancelCollect(ctx, ph.biz, req.PostId, req.CollectId, uc.Uid); err != nil {
ph.l.Error(PostCanceCollectError, zap.Error(err))
return Result{}, err
}
}
return Result{
Expand Down
2 changes: 1 addition & 1 deletion internal/api/post_req.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ type LikeReq struct {
type CollectReq struct {
PostId int64 `json:"postId,omitempty"`
CollectId int64 `json:"collectId,omitempty"`
Collect bool `json:"collect,omitempty"`
Collectd bool `json:"collectd,omitempty"`
}
1 change: 0 additions & 1 deletion internal/domain/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ type Post struct {
CategoryID int64
Tags string
CommentCount int64
ViewCount int64
}

type Interactive struct {
Expand Down
4 changes: 4 additions & 0 deletions internal/repository/dao/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dao

import (
. "LinkMe/internal/repository/models"

"gorm.io/gorm"
)

Expand All @@ -10,5 +11,8 @@ func InitTables(db *gorm.DB) error {
return db.AutoMigrate(
&User{},
&Post{},
&Interactive{},
&UserCollectionBiz{},
&UserLikeBiz{},
)
}
188 changes: 167 additions & 21 deletions internal/repository/dao/interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@ package dao
import (
. "LinkMe/internal/repository/models"
"context"
"errors"
"log"
"time"

"go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)

var (
ErrRecordNotFound = gorm.ErrRecordNotFound
ErrRecordNotFound = gorm.ErrRecordNotFound
StatusLiked = 1
StatusUnliked = 0
StatusCollection = 1
StatusUnCollection = 0
)

// InteractiveDAO 互动数据访问对象接口
Expand All @@ -28,62 +36,200 @@ type InteractiveDAO interface {

type interactiveDAO struct {
db *gorm.DB
l *zap.Logger
}

func NewInteractiveDAO(db *gorm.DB) InteractiveDAO {
return &interactiveDAO{db: db}
func NewInteractiveDAO(db *gorm.DB, l *zap.Logger) InteractiveDAO {
return &interactiveDAO{
db: db,
l: l,
}
}

func (i *interactiveDAO) getCurrentTime() int64 {
return time.Now().UnixMilli()
}

// IncrReadCnt 增加阅读计数
func (i *interactiveDAO) IncrReadCnt(ctx context.Context, biz string, bizId int64) error {
//TODO implement me
panic("implement me")
now := i.getCurrentTime()
// 创建Interactive实例,用于存储阅读计数更新
interactive := Interactive{
BizName: biz,
BizID: bizId,
ReadCount: 1,
CreateTime: now,
UpdateTime: now,
}
// 使用Clauses处理数据库冲突,即在记录已存在时更新阅读计数
return i.db.WithContext(ctx).Clauses(clause.OnConflict{
DoUpdates: clause.Assignments(map[string]interface{}{
"read_count": gorm.Expr("read_count + 1"),
"update_at": now,
}),
}).Create(&interactive).Error
}

func (i *interactiveDAO) BatchIncrReadCnt(ctx context.Context, biz []string, bizIds []int64) error {
//TODO implement me
panic("implement me")
}

// InsertLikeInfo 插入用户点赞信息和相关互动信息
func (i *interactiveDAO) InsertLikeInfo(ctx context.Context, lb UserLikeBiz) error {
//TODO implement me
panic("implement me")
now := i.getCurrentTime()
return i.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 检查点赞是否存在
existingLike := UserLikeBiz{}
err := tx.Where("uid = ? AND biz_id = ? AND biz_name = ?", lb.Uid, lb.BizID, lb.BizName).First(&existingLike).Error
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
i.l.Error("query record filed", zap.Error(err))
return err
}
// 创建新的点赞记录
lb.CreateTime = now
lb.UpdateTime = now
lb.Status = StatusLiked
if er := tx.Create(&lb).Error; er != nil {
i.l.Error("create user like record filed ")
return er
}
} else {
// 更新现有的点赞记录
existingLike.Status = StatusLiked
existingLike.UpdateTime = now
if er := tx.Save(&existingLike).Error; er != nil {
i.l.Error("update user like record filed")
return er
}
}
// 更新互动信息中的点赞计数
return tx.Clauses(clause.OnConflict{
DoUpdates: clause.Assignments(map[string]interface{}{
"like_count": gorm.Expr("`like_count` + 1"),
"updated_at": now,
}),
}).Create(&Interactive{
BizName: lb.BizName,
BizID: lb.BizID,
LikeCount: 1,
UpdateTime: now,
CreateTime: now,
}).Error
})
}

// DeleteLikeInfo 删除用户点赞信息和相关互动信息
func (i *interactiveDAO) DeleteLikeInfo(ctx context.Context, lb UserLikeBiz) error {
//TODO implement me
panic("implement me")
now := i.getCurrentTime()
return i.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 如果出现冲突,则更新updated_at和status字段
err := tx.WithContext(ctx).Model(&UserLikeBiz{}).Where("uid = ? AND biz_id = ? AND biz_name = ?", lb.Uid, lb.BizID, lb.BizName).Updates(map[string]interface{}{
"updated_at": now,
"status": StatusUnliked,
}).Error
if err != nil {
i.l.Error("delete user like filed")
return err
}
return tx.WithContext(ctx).Model(&Interactive{}).Where("biz_name = ? AND biz_id = ?", lb.BizName, lb.BizID).Updates(map[string]interface{}{
"like_count": gorm.Expr("`like_count` - 1"),
"updated_at": now,
}).Error
})
}

// InsertCollectionBiz 插入用户收藏信息和相关互动信息
func (i *interactiveDAO) InsertCollectionBiz(ctx context.Context, cb UserCollectionBiz) error {
//TODO implement me
panic("implement me")
now := i.getCurrentTime()
return i.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 检查用户是否已经收藏了该业务
existingCollection := UserCollectionBiz{}
err := tx.Where("uid = ? AND biz_id = ? AND biz_name = ?", cb.Uid, cb.BizID, cb.BizName).First(&existingCollection).Error
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
i.l.Error("query record failed", zap.Error(err))
return err
}
// 创建新的收藏记录
cb.CreateTime = now
cb.UpdateTime = now
cb.Status = StatusCollection
if er := tx.Create(&cb).Error; er != nil {
i.l.Error("create user collection record failed", zap.Error(er))
return er
}
log.Println(cb.Status)
} else {
// 更新现有的收藏记录
existingCollection.Status = StatusCollection
existingCollection.UpdateTime = now
if er := tx.Save(&existingCollection).Error; er != nil {
i.l.Error("update user collection record failed", zap.Error(er))
return er
}
log.Println(cb.Status)
}
// 更新互动记录的收藏数
return tx.Clauses(clause.OnConflict{
DoUpdates: clause.Assignments(map[string]interface{}{
"collect_count": gorm.Expr("`collect_count` + 1"),
"updated_at": now,
}),
}).Create(&Interactive{
BizName: cb.BizName,
BizID: cb.BizID,
CollectCount: 1,
UpdateTime: now,
CreateTime: now,
}).Error
})
}

// DeleteCollectionBiz 删除用户收藏信息和相关互动信息
func (i *interactiveDAO) DeleteCollectionBiz(ctx context.Context, cb UserCollectionBiz) error {
//TODO implement me
panic("implement me")
now := i.getCurrentTime()
return i.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 更新用户收藏信息
err := tx.WithContext(ctx).Model(&UserCollectionBiz{}).Where("uid = ? AND biz_id = ? AND biz_name = ? AND collection_id = ?", cb.Uid, cb.BizID, cb.BizName, cb.CollectionId).Updates(map[string]interface{}{
"updated_at": now,
"status": StatusUnCollection,
}).Error
if err != nil {
i.l.Error("delete user collection filed")
return err
}
// 更新互动信息
return tx.WithContext(ctx).Model(&Interactive{}).Where("biz_name = ? AND biz_id = ?", cb.BizName, cb.BizID).Updates(map[string]interface{}{
"collect_count": gorm.Expr("`collect_count` - 1"),
"updated_at": now,
}).Error
})
}

func (i *interactiveDAO) GetLikeInfo(ctx context.Context, biz string, id int64, uid int64) (UserLikeBiz, error) {
//TODO implement me
panic("implement me")
var lb UserLikeBiz
err := i.db.WithContext(ctx).Where("uid = ? AND biz_name = ? AND biz_id = ? AND status = ?", uid, biz, id, 1).First(&lb).Error
return lb, err
}

func (i *interactiveDAO) GetCollectInfo(ctx context.Context, biz string, id int64, uid int64) (UserCollectionBiz, error) {
//TODO implement me
panic("implement me")
var cb UserCollectionBiz
err := i.db.WithContext(ctx).Where("uid = ? AND biz_name = ? AND biz_id = ? AND status = ?", uid, biz, id, 1).First(&cb).Error
return cb, err
}

func (i *interactiveDAO) Get(ctx context.Context, biz string, id int64) (Interactive, error) {
//TODO implement me
panic("implement me")
var inc Interactive
err := i.db.WithContext(ctx).Where("biz_name = ? AND biz_id = ?", biz, id).First(&inc).Error
return inc, err
}

func (i *interactiveDAO) GetByIds(ctx context.Context, biz string, ids []int64) ([]Interactive, error) {
//TODO implement me
panic("implement me")
var inc []Interactive
err := i.db.WithContext(ctx).
Where("biz_name = ? AND biz_id IN ?", biz, ids).
First(&inc).Error
return inc, err
}
15 changes: 8 additions & 7 deletions internal/repository/interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ import (
"LinkMe/internal/repository/dao"
"LinkMe/internal/repository/models"
"context"
"errors"

"go.uber.org/zap"
)

type InteractiveRepository interface {
IncrReadCnt(ctx context.Context, biz string, id int64) error
// biz 和 bizId 长度必须一致
// BatchIncrReadCnt biz 和 bizId 长度必须一致
BatchIncrReadCnt(ctx context.Context, biz []string, id []int64) error // 批量更新阅读计数(与kafka配合使用)
IncrLike(ctx context.Context, biz string, id int64, uid int64) error // 增加阅读计数
DecrLike(ctx context.Context, biz string, id int64, uid int64) error // 减少阅读计数
Expand Down Expand Up @@ -86,11 +87,11 @@ func (c *CachedInteractiveRepository) Get(ctx context.Context, biz string, id in

func (c *CachedInteractiveRepository) Liked(ctx context.Context, biz string, id int64, uid int64) (bool, error) {
_, err := c.dao.GetLikeInfo(ctx, biz, id, uid)
switch err {
case nil:
switch {
case err == nil:
// 如果没有错误,说明找到了点赞记录,返回true
return true, nil
case dao.ErrRecordNotFound:
case errors.Is(err, dao.ErrRecordNotFound):
// 如果错误是ErrRecordNotFound,说明没有找到点赞记录
c.l.Error(PostGetLikedERROR, zap.Error(err))
return false, nil
Expand All @@ -102,11 +103,11 @@ func (c *CachedInteractiveRepository) Liked(ctx context.Context, biz string, id

func (c *CachedInteractiveRepository) Collected(ctx context.Context, biz string, id int64, uid int64) (bool, error) {
_, err := c.dao.GetCollectInfo(ctx, biz, id, uid)
switch err {
case nil:
switch {
case err == nil:
// 如果没有错误,说明找到了收藏记录,返回true
return true, nil
case dao.ErrRecordNotFound:
case errors.Is(err, dao.ErrRecordNotFound):
// 如果错误是ErrRecordNotFound,说明没有找到收藏记录
c.l.Error(PostGetCollectERROR, zap.Error(err))
return false, nil
Expand Down
21 changes: 12 additions & 9 deletions internal/repository/models/interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ type UserLikeBiz struct {
BizID int64 `gorm:"index"`
BizName string
Status int
UpdateTime int64
CreateTime int64
UpdateTime int64 `gorm:"column:updated_at;type:bigint;not null;index"`
CreateTime int64 `gorm:"column:created_at;type:bigint"`
Deleted bool `gorm:"column:deleted;default:false"`
}

// UserCollectionBiz 用户收藏业务结构体
Expand All @@ -17,19 +18,21 @@ type UserCollectionBiz struct {
Uid int64 `gorm:"index"`
BizID int64 `gorm:"index"`
BizName string
Status int `gorm:"column:status"`
CollectionId int64 `gorm:"index"`
UpdateTime int64
CreateTime int64
UpdateTime int64 `gorm:"column:updated_at;type:bigint;not null;index"`
CreateTime int64 `gorm:"column:created_at;type:bigint"`
Deleted bool `gorm:"column:deleted;default:false"`
}

// Interactive 互动信息结构体
type Interactive struct {
ID int64 `gorm:"primaryKey;autoIncrement"`
BizID int64 `gorm:"uniqueIndex:biz_type_id"`
BizName string `gorm:"type:varchar(128);uniqueIndex:biz_type_id"`
ReadCount int64
LikeCount int64
CollectCount int64
UpdateTime int64
CreateTime int64
ReadCount int64 `gorm:"column:read_count"`
LikeCount int64 `gorm:"column:like_count"`
CollectCount int64 `gorm:"column:collect_count"`
UpdateTime int64 `gorm:"column:updated_at;type:bigint;not null;index"`
CreateTime int64 `gorm:"column:created_at;type:bigint"`
}
Loading

0 comments on commit bc18181

Please sign in to comment.