56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
'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);
|
|
},
|
|
}));
|