in firestore/FirestoreSwiftUIExample/ViewModels/RestaurantViewModel.swift [38:80]
func add(review: Review) {
db.runTransaction({ (transaction, errorPointer) -> Any? in
let restaurantRef = self.restaurant.reference!
let restaurantDocument: DocumentSnapshot
do {
try restaurantDocument = transaction.getDocument(restaurantRef)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let ratingCount = restaurantDocument.data()?["numRatings"] as? Int else {
errorPointer?.pointee = self.getNSError(document: restaurantDocument)
return nil
}
guard let averageRating = restaurantDocument.data()?["avgRating"] as? Float else {
errorPointer?.pointee = self.getNSError(document: restaurantDocument)
return nil
}
let newAverage = (Float(ratingCount) * averageRating + Float(review.rating))
/ Float(ratingCount + 1)
transaction.setData([
"numRatings": ratingCount + 1,
"avgRating": newAverage,
], forDocument: restaurantRef, merge: true)
let reviewDocument = self.restaurant.ratingsCollection!.document()
do {
_ = try transaction.setData(from: review, forDocument: reviewDocument)
} catch {
fatalError("Unable to add review: \(error.localizedDescription).")
}
return nil
}) { object, error in
if let error = error {
print("Transaction failed: \(error)")
}
}
}