前端:

增加会话缓存
后端:
增加触发消息创建事件
增加消息创建事件触发后的处理函数
This commit is contained in:
2026-01-20 23:09:46 +08:00
parent be621e9ae2
commit bedcf97c9d
11 changed files with 158 additions and 88 deletions
-1
View File
@@ -24,7 +24,6 @@ export const useChatStore = defineStore('chat', {
this.messages = [];
//先从浏览器缓存加载一部分消息列表
const localHistory = await messagesDb.getPageMessages(sessionId, new Date().toISOString(), this.pageSize);
console.log(localHistory)
if (localHistory.length > 0) {
this.messages = localHistory;
} else {
+63
View File
@@ -0,0 +1,63 @@
import { defineStore } from "pinia";
import { messageService } from "@/services/message";
import { conversationDb } from "@/utils/db/conversationDB";
import { useMessage } from "@/components/messages/useAlert";
const message = useMessage();
export const useConversationStore = defineStore('conversation', {
state: () => ({
conversations: []
}),
actions: {
async addConversation(conversation) {
await conversationDb.save(conversation);
this.conversations.unshift(conversation)
},
/**
* 加载当前会话消息列表
*/
async loadUserConversations() {
if (this.conversations.length == 0) {
try {
const covnersationsCache = await conversationDb.getAll();
if (covnersationsCache && covnersationsCache.length > 0) {
covnersationsCache.sort((a, b) => {
return new Date(a.dateTime) - new Date(b.dateTime);
})
}
} catch (e) {
message.error('读取本地会话缓存失败...');
console.log('读取本地会话缓存失败:', e);
}
}
await this.fetchConversationsFromServier()
},
/**
* 从服务器加载新消息
* @param {*} sessionId
* @returns
*/
async fetchConversationsFromServier() {
const newConversations = (await messageService.getConversations()).data;
if (newConversations.length > 0) {
// 1. 将当前的本地数据转为 Map,方便通过 ID 快速查找 (O(1) 复杂度)
const localMap = new Map(this.conversations.map(item => [item.id, item]));
newConversations.forEach(item => {
const existingItem = localMap.get(item.id);
if (existingItem) {
// --- 局部更新 ---
// 使用 Object.assign 将新数据合并到旧对象上,保持响应式引用
Object.assign(existingItem, item);
} else {
// --- 插入新会话 ---
this.conversations.unshift(item);
}
// 同步到本地数据库
conversationDb.save(item);
});
}
}
}
})