diff --git a/src/lib/services/upcoming-sync.ts b/src/lib/services/upcoming-sync.ts index 5f0f52b..0a024e3 100644 --- a/src/lib/services/upcoming-sync.ts +++ b/src/lib/services/upcoming-sync.ts @@ -86,19 +86,43 @@ export async function checkAndSyncUpcomingSlots(): Promise { .sort((a, b) => b.count - a.count) .slice(0, targetUniqueCount); - await UpcomingSlot.findOneAndUpdate( - {}, - { $set: { slot: scheduledSlot, lastSyncedDate: today } }, - { upsert: true, new: true, setDefaultsOnInsert: true }, - ); - - await UpcomingSubject.deleteMany({}); - if (ranked.length > 0) { - await UpcomingSubject.insertMany( + const todaysSlot = { $set: { slot: scheduledSlot, lastSyncedDate: today } }; + const wonTheSync = currentSlotDoc + ? await UpcomingSlot.findOneAndUpdate( + { _id: currentSlotDoc._id, lastSyncedDate: { $ne: today } }, + todaysSlot, + ) + : await UpcomingSlot.findOneAndUpdate({}, todaysSlot, { + upsert: true, + new: true, + setDefaultsOnInsert: true, + }); + + if (!wonTheSync) return; + + try { + const freshSubjects = await UpcomingSubject.insertMany( ranked.map((item) => ({ subject: item.subject, slots: item.slots, })), ); + + await UpcomingSubject.deleteMany({ + _id: { $nin: freshSubjects.map((subject) => subject._id) }, + }); + } catch (error) { + await UpcomingSlot.updateOne( + { _id: wonTheSync._id, lastSyncedDate: today }, + currentSlotDoc?.lastSyncedDate + ? { + $set: { + slot: currentSlotDoc.slot, + lastSyncedDate: currentSlotDoc.lastSyncedDate, + }, + } + : { $unset: { lastSyncedDate: 1 } }, + ); + throw error; } }