From 89b30bcf58bf3d296678c0dfe96a34211e8e68bc Mon Sep 17 00:00:00 2001 From: RockYang Date: Sun, 20 Aug 2023 19:06:18 +0800 Subject: [PATCH] opt: optimize code for remove chat item --- api/handler/chat_history_handler.go | 28 ++++++++++++++++++++-------- api/handler/chat_item_handler.go | 9 +++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/api/handler/chat_history_handler.go b/api/handler/chat_history_handler.go index 065fa896..17d4a517 100644 --- a/api/handler/chat_history_handler.go +++ b/api/handler/chat_history_handler.go @@ -6,6 +6,7 @@ import ( "chatplus/store/vo" "chatplus/utils" "chatplus/utils/resp" + "gorm.io/gorm" "github.com/gin-gonic/gin" ) @@ -75,19 +76,30 @@ func (h *ChatHandler) Clear(c *gin.Context) { resp.ERROR(c, "No chats found") return } - // 清空聊天记录 + + var chatIds = make([]string, 0) for _, chat := range chats { - err := h.db.Where("chat_id = ? AND user_id = ?", chat.ChatId, user.Id).Delete(&model.HistoryMessage{}) - if err != nil { - logger.Warnf("Failed to delele chat history for ChatID: %s", chat.ChatId) - } + chatIds = append(chatIds, 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 = ?", user.Id).Delete(&model.ChatItem{}) - if res.Error != nil { + res = h.db.Where("user_id = ? AND chat_id IN ?", user.Id, chatIds).Delete(&model.HistoryMessage{}) + 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.") return } diff --git a/api/handler/chat_item_handler.go b/api/handler/chat_item_handler.go index 75c52044..ab64dbc2 100644 --- a/api/handler/chat_item_handler.go +++ b/api/handler/chat_item_handler.go @@ -66,6 +66,15 @@ func (h *ChatHandler) Remove(c *gin.Context) { 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) resp.SUCCESS(c, types.OkMsg)