fix(小宝预警): 串行保存风险缓存
This commit is contained in:
@@ -35,6 +35,9 @@ async function loadInsights(): Promise<XiaobaoRiskInsightCacheItem[] | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
let snapshotSaveQueue: Promise<void> = Promise.resolve();
|
||||
let insightSaveQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
export const useXiaobaoRiskStore = create<XiaobaoRiskState>((set, get) => ({
|
||||
snapshots: [],
|
||||
insights: [],
|
||||
@@ -52,11 +55,15 @@ export const useXiaobaoRiskStore = create<XiaobaoRiskState>((set, get) => ({
|
||||
saveSnapshot: async (item) => {
|
||||
const optimistic = upsertDailySnapshot(get().snapshots, item);
|
||||
set({ snapshots: optimistic, error: undefined });
|
||||
try {
|
||||
const task = snapshotSaveQueue.then(async () => {
|
||||
const remote = await loadServerData<XiaobaoRiskSnapshot[]>('xiaobao-risk-snapshots');
|
||||
const snapshots = mergeDailySnapshotCacheForSave(optimistic, Array.isArray(remote) ? remote : [], item);
|
||||
const snapshots = mergeDailySnapshotCacheForSave(get().snapshots, Array.isArray(remote) ? remote : [], item);
|
||||
set({ snapshots, error: undefined });
|
||||
await saveServerData('xiaobao-risk-snapshots', snapshots);
|
||||
});
|
||||
snapshotSaveQueue = task.catch(() => undefined);
|
||||
try {
|
||||
await task;
|
||||
} catch (error) {
|
||||
set({ error: '小宝预警快照保存失败' });
|
||||
throw error;
|
||||
@@ -66,11 +73,15 @@ export const useXiaobaoRiskStore = create<XiaobaoRiskState>((set, get) => ({
|
||||
saveInsight: async (item) => {
|
||||
const optimistic = upsertInsight(get().insights, item);
|
||||
set({ insights: optimistic, error: undefined });
|
||||
try {
|
||||
const task = insightSaveQueue.then(async () => {
|
||||
const remote = await loadServerData<XiaobaoRiskInsightCacheItem[]>('xiaobao-risk-insights');
|
||||
const insights = mergeInsightCacheForSave(optimistic, Array.isArray(remote) ? remote : [], item);
|
||||
const insights = mergeInsightCacheForSave(get().insights, Array.isArray(remote) ? remote : [], item);
|
||||
set({ insights, error: undefined });
|
||||
await saveServerData('xiaobao-risk-insights', insights);
|
||||
});
|
||||
insightSaveQueue = task.catch(() => undefined);
|
||||
try {
|
||||
await task;
|
||||
} catch (error) {
|
||||
set({ error: '小宝预警解读保存失败' });
|
||||
throw error;
|
||||
|
||||
Reference in New Issue
Block a user