opt: optimize code for remove chat item

This commit is contained in:
RockYang 2023-08-20 19:06:18 +08:00
parent 473d8f5f85
commit 89b30bcf58
2 changed files with 29 additions and 8 deletions

View File

@ -6,6 +6,7 @@ import (
"chatplus/store/vo" "chatplus/store/vo"
"chatplus/utils" "chatplus/utils"
"chatplus/utils/resp" "chatplus/utils/resp"
"gorm.io/gorm"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -75,19 +76,30 @@ func (h *ChatHandler) Clear(c *gin.Context) {
resp.ERROR(c, "No chats found") resp.ERROR(c, "No chats found")
return return
} }
// 清空聊天记录
var chatIds = make([]string, 0)
for _, chat := range chats { for _, chat := range chats {
err := h.db.Where("chat_id = ? AND user_id = ?", chat.ChatId, user.Id).Delete(&model.HistoryMessage{}) chatIds = append(chatIds, chat.ChatId)
if err != nil {
logger.Warnf("Failed to delele chat history for ChatID: %s", chat.ChatId)
}
// 清空会话上下文 // 清空会话上下文
h.App.ChatContexts.Delete(chat.ChatId) h.App.ChatContexts.Delete(chat.ChatId)
} }
err = h.db.Transaction(func(tx *gorm.DB) error {
res := h.db.Where("user_id =?", user.Id).Delete(&model.ChatItem{})
if res.Error != nil {
return res.Error
}
// 删除所有的会话记录 res = h.db.Where("user_id = ? AND chat_id IN ?", user.Id, chatIds).Delete(&model.HistoryMessage{})
res = h.db.Where("user_id = ?", user.Id).Delete(&model.ChatItem{}) if res.Error != nil {
if res.Error != nil { return res.Error
}
// TODO: 是否要删除 MidJourney 绘画记录和图片文件?
return nil
})
if err != nil {
logger.Errorf("Error with delete chats: %+v", err)
resp.ERROR(c, "Failed to remove chat from database.") resp.ERROR(c, "Failed to remove chat from database.")
return return
} }

View File

@ -66,6 +66,15 @@ func (h *ChatHandler) Remove(c *gin.Context) {
return return
} }
// 删除当前会话的聊天记录
res = h.db.Where("user_id = ? AND chat_id =?", user.Id, chatId).Delete(&model.ChatItem{})
if res.Error != nil {
resp.ERROR(c, "Failed to remove chat from database.")
return
}
// TODO: 是否要删除 MidJourney 绘画记录和图片文件?
// 清空会话上下文 // 清空会话上下文
h.App.ChatContexts.Delete(chatId) h.App.ChatContexts.Delete(chatId)
resp.SUCCESS(c, types.OkMsg) resp.SUCCESS(c, types.OkMsg)