92 lines
2.0 KiB
Go
92 lines
2.0 KiB
Go
package service
|
|
|
|
import (
|
|
"errors"
|
|
"hepa-calc-admin-api/api/dao"
|
|
"hepa-calc-admin-api/api/model"
|
|
"hepa-calc-admin-api/global"
|
|
)
|
|
|
|
type UserCollectionService struct {
|
|
}
|
|
|
|
// GetUserCollectionQuestionStatus 检测用户收藏状态
|
|
func (r *UserCollectionService) GetUserCollectionQuestionStatus(userId, questionId int64) bool {
|
|
userCollectionDao := dao.UserCollectionDao{}
|
|
|
|
maps := make(map[string]interface{})
|
|
maps["user_id"] = userId
|
|
maps["question_id"] = questionId
|
|
userCollection, _ := userCollectionDao.GetUserCollection(maps)
|
|
if userCollection == nil {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// PutUserCollection 收藏题目
|
|
func (r *UserCollectionService) PutUserCollection(userId, questionId int64) (bool, error) {
|
|
// 检测用户收藏状态
|
|
IsCollection := r.GetUserCollectionQuestionStatus(userId, questionId)
|
|
if IsCollection == true {
|
|
// 已收藏
|
|
return true, nil
|
|
}
|
|
|
|
// 开始事务
|
|
tx := global.Db.Begin()
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
tx.Rollback()
|
|
}
|
|
}()
|
|
|
|
userCollection := &model.UserCollection{
|
|
UserId: userId,
|
|
QuestionId: questionId,
|
|
}
|
|
|
|
userCollectionDao := dao.UserCollectionDao{}
|
|
userCollection, err := userCollectionDao.AddUserCollection(tx, userCollection)
|
|
if err != nil {
|
|
tx.Rollback()
|
|
return false, errors.New("收藏失败")
|
|
}
|
|
|
|
tx.Commit()
|
|
return true, nil
|
|
}
|
|
|
|
// PutUserCollectionCancel 取消收藏题目
|
|
func (r *UserCollectionService) PutUserCollectionCancel(userId, questionId int64) (bool, error) {
|
|
// 检测用户收藏状态
|
|
IsCollection := r.GetUserCollectionQuestionStatus(userId, questionId)
|
|
if IsCollection == false {
|
|
// 已收藏
|
|
return true, nil
|
|
}
|
|
|
|
// 开始事务
|
|
tx := global.Db.Begin()
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
tx.Rollback()
|
|
}
|
|
}()
|
|
|
|
userCollectionDao := dao.UserCollectionDao{}
|
|
|
|
maps := make(map[string]interface{})
|
|
maps["user_id"] = userId
|
|
maps["question_id"] = questionId
|
|
err := userCollectionDao.DeleteUserCollection(tx, maps)
|
|
if err != nil {
|
|
tx.Rollback()
|
|
return false, errors.New("取消收藏失败")
|
|
}
|
|
|
|
tx.Commit()
|
|
return true, nil
|
|
}
|