You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
2.0 KiB
72 lines
2.0 KiB
/**
|
|
* 本地缓存模块 - localStorage 封装,按 integrateId 隔离
|
|
*/
|
|
import { ChatMessage, CacheData } from './types';
|
|
import { logger } from './logger';
|
|
|
|
const STORAGE_PREFIX = 'csk_history_';
|
|
const MAX_MESSAGES = 200;
|
|
const TRIM_COUNT = 50;
|
|
|
|
/** 生成存储 key */
|
|
function storageKey(integrateId: string): string {
|
|
return `${STORAGE_PREFIX}${integrateId}`;
|
|
}
|
|
|
|
/**
|
|
* 保存消息到 localStorage
|
|
*/
|
|
export function saveMessages(integrateId: string, messages: ChatMessage[]): void {
|
|
try {
|
|
// 消息上限裁剪:保留最新 200 条,超出裁剪最早 50 条
|
|
let trimmed = messages;
|
|
if (trimmed.length > MAX_MESSAGES) {
|
|
trimmed = trimmed.slice(TRIM_COUNT);
|
|
logger.warn(`消息数量达到上限,已裁剪最早 ${TRIM_COUNT} 条,当前 ${trimmed.length} 条`);
|
|
}
|
|
|
|
const data: CacheData = {
|
|
messages: trimmed,
|
|
updatedAt: Date.now(),
|
|
};
|
|
localStorage.setItem(storageKey(integrateId), JSON.stringify(data));
|
|
} catch (e) {
|
|
if (e instanceof Error && e.name === 'QuotaExceededError') {
|
|
logger.error('localStorage 空间不足,会话历史保存失败。建议清空历史记录。');
|
|
} else {
|
|
logger.error('保存会话历史失败', e);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 从 localStorage 加载消息
|
|
*/
|
|
export function loadMessages(integrateId: string): ChatMessage[] {
|
|
try {
|
|
const raw = localStorage.getItem(storageKey(integrateId));
|
|
if (!raw) {
|
|
return [];
|
|
}
|
|
const data: CacheData = JSON.parse(raw);
|
|
if (!data || !Array.isArray(data.messages)) {
|
|
return [];
|
|
}
|
|
logger.info(`加载历史消息 integrateId=${integrateId} count=${data.messages.length}`);
|
|
return data.messages;
|
|
} catch (e) {
|
|
logger.warn('加载会话历史失败', e);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 清空指定 integrateId 的本地缓存
|
|
*/
|
|
export function clearMessages(integrateId: string): void {
|
|
try {
|
|
localStorage.removeItem(storageKey(integrateId));
|
|
} catch (e) {
|
|
logger.warn('清空会话历史失败', e);
|
|
}
|
|
}
|