knowledge-api/api/service/Question.go
2024-06-19 14:30:11 +08:00

123 lines
2.6 KiB
Go

package service
import (
"errors"
"knowledge/api/dao"
"knowledge/api/model"
"knowledge/api/requests"
"knowledge/global"
"knowledge/utils"
"strconv"
"strings"
)
type QuestionService struct {
}
// AddQuestion 新增题目
func (r *QuestionService) AddQuestion(req requests.AddQuestion) (bool, error) {
// 验证一级标签
firstLabelId, err := strconv.ParseInt(req.FirstLabelId, 10, 64)
if err != nil {
return false, err
}
labelDao := dao.LabelDao{}
_, err = labelDao.GetLabelFirstById(firstLabelId)
if err != nil {
return false, err
}
// 验证二级标签
var secondLabelId int64
if req.SecondLabelId != "" {
secondLabelId, err := strconv.ParseInt(req.SecondLabelId, 10, 64)
if err != nil {
return false, err
}
_, err = labelDao.GetLabelFirstById(secondLabelId)
if err != nil {
return false, err
}
}
// 处理图片
var questionImage string
if len(req.QuestionImage) > 0 {
result := make([]string, len(req.QuestionImage))
for i, url := range req.QuestionImage {
result[i] = utils.RemoveOssDomain(url)
}
questionImage = strings.Join(result, ",")
}
// 判断选项
if req.QuestionType == 1 || req.QuestionType == 2 {
if len(req.QuestionOption) == 0 {
return false, errors.New("请填入选项")
}
}
// 验证重复
questionDao := dao.QuestionDao{}
maps := make(map[string]interface{})
maps["question_name"] = req.QuestionName
question, _ := questionDao.GetQuestion(maps)
if question != nil {
return false, errors.New("题目名称重复")
}
// 开始事务
tx := global.Db.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
// 新增题目
question = &model.Question{
QuestionName: req.QuestionName,
QuestionType: req.QuestionType,
QuestionStatus: req.QuestionStatus,
QuestionSource: req.QuestionSource,
QuestionImage: questionImage,
QuestionAnswer: req.QuestionAnswer,
QuestionAnalysis: req.QuestionAnalysis,
Difficulty: req.Difficulty,
FirstLabelId: &firstLabelId,
SecondLabelId: nil,
}
if req.SecondLabelId != "" {
question.SecondLabelId = &secondLabelId
}
question, err = questionDao.AddQuestion(tx, question)
if err != nil {
tx.Rollback()
return false, errors.New("新增失败")
}
// 新增选项
questionOptionDao := dao.QuestionOptionDao{}
for _, s := range req.QuestionOption {
questionOption := &model.QuestionOption{
QuestionId: question.QuestionId,
OptionValue: s,
}
questionOption, err := questionOptionDao.AddQuestionOption(tx, questionOption)
if err != nil {
tx.Rollback()
return false, errors.New("新增失败")
}
}
//tx.Commit()
return true, nil
}