Files
digital-pilates/services/aiCoachSession.ts
richarjiang 2357596665 refactor(storage): 迁移 AsyncStorage 至 expo-sqlite/kv-store
- 统一替换所有 @react-native-async-storage/async-storage 导入为自定义 kvStore
- 新增 kvStore.ts 封装 expo-sqlite/kv-store,保持与 AsyncStorage 完全兼容
- 新增同步读写方法,提升性能
- 引入 expo-sqlite 依赖并更新 lock 文件

BREAKING CHANGE: 移除 @react-native-async-storage/async-storage 依赖,需重新安装依赖并清理旧数据
2025-09-15 12:51:18 +08:00

52 lines
1.3 KiB
TypeScript

import AsyncStorage from '@/utils/kvStore';
export type AiCoachChatMessage = {
id: string;
role: 'user' | 'assistant';
content: string;
attachments?: any[];
choices?: any[];
interactionType?: string;
pendingData?: any;
context?: any;
};
export type AiCoachSessionCache = {
conversationId?: string;
messages: AiCoachChatMessage[];
updatedAt: number;
};
const STORAGE_KEY = '@ai_coach_session_v1';
export async function loadAiCoachSessionCache(): Promise<AiCoachSessionCache | null> {
try {
const s = await AsyncStorage.getItem(STORAGE_KEY);
if (!s) return null;
const obj = JSON.parse(s) as AiCoachSessionCache;
if (!obj || !Array.isArray(obj.messages)) return null;
return obj;
} catch {
return null;
}
}
export async function saveAiCoachSessionCache(cache: AiCoachSessionCache): Promise<void> {
try {
const payload: AiCoachSessionCache = {
conversationId: cache.conversationId,
messages: cache.messages?.slice?.(-200) ?? [], // 限制最多缓存 200 条,避免无限增长
updatedAt: Date.now(),
};
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
} catch { }
}
export async function clearAiCoachSessionCache(): Promise<void> {
try {
await AsyncStorage.removeItem(STORAGE_KEY);
} catch { }
}