Skip to content

Commit 4e1c164

Browse files
committed
feat: 事项重复ID校验
1 parent 56b12b4 commit 4e1c164

1 file changed

Lines changed: 36 additions & 3 deletions

File tree

apps/rn-calendar/src/services/EventStorage.ts

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,37 @@ export class EventStorage {
6969
memoryCache = data;
7070
}
7171

72+
/**
73+
* 检查事项 ID 是否已存在(跨所有日期)
74+
*/
75+
private static eventIdExists(all: EventsByDate, eventId: string): boolean {
76+
for (const dateEvents of Object.values(all)) {
77+
if (dateEvents.some(e => e.id === eventId)) {
78+
return true;
79+
}
80+
}
81+
return false;
82+
}
83+
7284
static async addEvent(input: CreateCalendarEventInput): Promise<CalendarEvent> {
7385
const now = new Date().toISOString();
86+
let eventId = generateId();
87+
88+
const all = await EventStorage.getAllEventsByDate();
89+
90+
// 确保生成唯一的 ID(理论上 generateId 应该已经唯一,但做双重保险)
91+
let attempts = 0;
92+
while (EventStorage.eventIdExists(all, eventId) && attempts < 10) {
93+
eventId = generateId();
94+
attempts++;
95+
}
96+
97+
if (attempts >= 10) {
98+
console.warn('EventStorage: 多次尝试生成唯一 ID 失败');
99+
}
100+
74101
const event: CalendarEvent = {
75-
id: generateId(),
102+
id: eventId,
76103
date: input.date,
77104
title: input.title.trim(),
78105
description: input.description?.trim(),
@@ -87,8 +114,14 @@ export class EventStorage {
87114
updatedAt: now,
88115
};
89116

90-
const all = await EventStorage.getAllEventsByDate();
91-
const nextForDate = [...(all[input.date] ?? []), event];
117+
// 检查同一日期下是否已存在相同 ID(防御性编程)
118+
const dateList = all[input.date] ?? [];
119+
if (dateList.some(e => e.id === event.id)) {
120+
console.warn(`EventStorage: 事项 ID ${event.id} 已存在于日期 ${input.date},跳过添加`);
121+
return dateList.find(e => e.id === event.id)!;
122+
}
123+
124+
const nextForDate = [...dateList, event];
92125
all[input.date] = nextForDate;
93126

94127
await EventStorage.persistAndUpdateCache(all);

0 commit comments

Comments
 (0)