feat(小宝预警): 增加趋势与解读缓存
This commit is contained in:
55
apps/web/stores/useXiaobaoRiskStore.ts
Normal file
55
apps/web/stores/useXiaobaoRiskStore.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
import { create } from 'zustand';
|
||||
import { loadServerData, saveServerData } from '@/lib/server-data';
|
||||
import {
|
||||
upsertDailySnapshot,
|
||||
upsertInsight,
|
||||
type XiaobaoRiskInsightCacheItem,
|
||||
} from '@/lib/xiaobao-risk-cache';
|
||||
import type { XiaobaoRiskSnapshot } from '@/lib/xiaobao-risk-trend';
|
||||
|
||||
interface XiaobaoRiskState {
|
||||
snapshots: XiaobaoRiskSnapshot[];
|
||||
insights: XiaobaoRiskInsightCacheItem[];
|
||||
fetchRiskData: () => Promise<void>;
|
||||
saveSnapshot: (item: XiaobaoRiskSnapshot) => Promise<void>;
|
||||
saveInsight: (item: XiaobaoRiskInsightCacheItem) => Promise<void>;
|
||||
}
|
||||
|
||||
async function loadSnapshots(): Promise<XiaobaoRiskSnapshot[]> {
|
||||
try {
|
||||
const rows = await loadServerData<XiaobaoRiskSnapshot[]>('xiaobao-risk-snapshots');
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
} catch {}
|
||||
return [];
|
||||
}
|
||||
|
||||
async function loadInsights(): Promise<XiaobaoRiskInsightCacheItem[]> {
|
||||
try {
|
||||
const rows = await loadServerData<XiaobaoRiskInsightCacheItem[]>('xiaobao-risk-insights');
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
} catch {}
|
||||
return [];
|
||||
}
|
||||
|
||||
export const useXiaobaoRiskStore = create<XiaobaoRiskState>((set, get) => ({
|
||||
snapshots: [],
|
||||
insights: [],
|
||||
|
||||
fetchRiskData: async () => {
|
||||
const [snapshots, insights] = await Promise.all([loadSnapshots(), loadInsights()]);
|
||||
set({ snapshots, insights });
|
||||
},
|
||||
|
||||
saveSnapshot: async (item) => {
|
||||
const snapshots = upsertDailySnapshot(get().snapshots, item);
|
||||
set({ snapshots });
|
||||
await saveServerData('xiaobao-risk-snapshots', snapshots);
|
||||
},
|
||||
|
||||
saveInsight: async (item) => {
|
||||
const insights = upsertInsight(get().insights, item);
|
||||
set({ insights });
|
||||
await saveServerData('xiaobao-risk-insights', insights);
|
||||
},
|
||||
}));
|
||||
Reference in New Issue
Block a user