fix(polls): fetch existing CloudKit record before updating vote

When updating a vote, CloudKit requires the server's changeTag to modify
existing records. Creating a new CKRecord caused "record to insert already
exists" errors. Now fetches the existing record first before saving.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Trey t
2026-01-14 23:59:40 -06:00
parent aa34c6585a
commit 57eab22746

View File

@@ -234,13 +234,26 @@ actor PollService {
throw PollError.notPollOwner // Using this error for now - voter can only update own vote
}
var updatedVote = vote
updatedVote.modifiedAt = Date()
// Fetch the existing record to get the server's changeTag
let recordID = CKRecord.ID(recordName: vote.id.uuidString)
let existingRecord: CKRecord
do {
existingRecord = try await publicDatabase.record(for: recordID)
} catch let error as CKError {
throw mapCloudKitError(error)
} catch {
throw PollError.unknown(error)
}
let ckVote = CKPollVote(vote: updatedVote)
// Update the fields on the fetched record
let now = Date()
existingRecord[CKPollVote.rankingsKey] = vote.rankings
existingRecord[CKPollVote.modifiedAtKey] = now
do {
try await publicDatabase.save(ckVote.record)
try await publicDatabase.save(existingRecord)
var updatedVote = vote
updatedVote.modifiedAt = now
return updatedVote
} catch let error as CKError {
throw mapCloudKitError(error)