IM/frontend/web/src/stores/conversation.js
nanxun bedcf97c9d 前端:
增加会话缓存
后端:
增加触发消息创建事件
增加消息创建事件触发后的处理函数
2026-01-20 23:09:46 +08:00

63 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
});
}
}
}
})