88 lines
2.6 KiB
Go
88 lines
2.6 KiB
Go
package commentlikemod
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
"videoweb/pub/common/log"
|
|
"videoweb/pub/common/srvdef"
|
|
"videoweb/pub/mongos"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
const collectionName = "comment_like"
|
|
|
|
const CollectionName = collectionName
|
|
|
|
type CommentLike struct {
|
|
UserId int64 `bson:"userId"`
|
|
CommentId int64 `bson:"commentId"`
|
|
CreatedAt time.Time `bson:"createdAt"`
|
|
}
|
|
|
|
var coll *mongos.Collection
|
|
|
|
func Init(ctx context.Context) {
|
|
coll = mongos.Shop.Coll(collectionName)
|
|
indexes := []mongo.IndexModel{
|
|
{Keys: bson.D{{Key: "userId", Value: 1}, {Key: "commentId", Value: 1}}, Options: options.Index().SetUnique(true)},
|
|
{Keys: bson.D{{Key: "commentId", Value: 1}}},
|
|
}
|
|
if _, err := coll.CreateIndex(ctx, indexes); err != nil {
|
|
panic(fmt.Sprintf("commentlikemod.Init CreateIndex failed: %v", err))
|
|
}
|
|
}
|
|
|
|
// Add 新增点赞关系,重复点赞不改变状态
|
|
func Add(ctx context.Context, userId, commentId int64) (bool, *srvdef.SrvErr) {
|
|
_, err := coll.InsertOne(ctx, &CommentLike{UserId: userId, CommentId: commentId, CreatedAt: time.Now()})
|
|
if mongo.IsDuplicateKeyError(err) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
log.Warn("commentlikemod.Add", log.E(err))
|
|
return false, srvdef.New(srvdef.ErrDbInsertError, "", "")
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// Remove 删除点赞关系,重复取消不改变状态
|
|
func Remove(ctx context.Context, userId, commentId int64) (bool, *srvdef.SrvErr) {
|
|
count, err := coll.DeleteOne(ctx, bson.M{"userId": userId, "commentId": commentId})
|
|
if err != nil {
|
|
log.Warn("commentlikemod.Remove", log.E(err))
|
|
return false, srvdef.New(srvdef.ErrDbDeleteError, "", "")
|
|
}
|
|
return count > 0, nil
|
|
}
|
|
|
|
// FindByUserAndComments 批量查询当前用户的评论点赞关系
|
|
func FindByUserAndComments(ctx context.Context, userId int64, commentIds []int64) ([]CommentLike, *srvdef.SrvErr) {
|
|
result := make([]CommentLike, 0)
|
|
if userId <= 0 || len(commentIds) == 0 {
|
|
return result, nil
|
|
}
|
|
err := coll.Find(ctx, &result, bson.M{"userId": userId, "commentId": bson.M{"$in": commentIds}})
|
|
if err != nil {
|
|
log.Warn("commentlikemod.FindByUserAndComments", log.E(err))
|
|
return nil, srvdef.New(srvdef.ErrDbQueryError, "", "")
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// DeleteByCommentIds 清理已删除评论的点赞关系
|
|
func DeleteByCommentIds(ctx context.Context, commentIds []int64) *srvdef.SrvErr {
|
|
if len(commentIds) == 0 {
|
|
return nil
|
|
}
|
|
_, err := coll.DeleteMany(ctx, bson.M{"commentId": bson.M{"$in": commentIds}})
|
|
if err != nil {
|
|
log.Warn("commentlikemod.DeleteByCommentIds", log.E(err))
|
|
return srvdef.New(srvdef.ErrDbDeleteError, "", "")
|
|
}
|
|
return nil
|
|
}
|