Skip to content

Instantly share code, notes, and snippets.

@quangtqag
Last active May 8, 2019 09:28
Show Gist options
  • Save quangtqag/0e0c245b6f4b910053c844a102fa5b4f to your computer and use it in GitHub Desktop.
Save quangtqag/0e0c245b6f4b910053c844a102fa5b4f to your computer and use it in GitHub Desktop.
// Create users and update users counter
private func populateUsers(addedCount: Int) {
let db = Firestore.firestore()
db.runTransaction({ (transaction, errorPointer) -> Any? in
// Update user counter to added users amount
let usersCounterRef = db.collection("counters").document("users")
let usersCounterDoc: DocumentSnapshot
do {
try usersCounterDoc = transaction.getDocument(usersCounterRef)
}
catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldCount = usersCounterDoc.data()?["count"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(usersCounterDoc)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
transaction.updateData(["count": oldCount + addedCount], forDocument: usersCounterRef)
// Create users
for _ in 0..<addedCount {
let userRef = db.collection("users").document()
transaction.setData(User.fake().dictionary, forDocument: userRef)
}
return nil
})
{ (object, error) in
if let error = error {
print("Transaction failed: \(error)")
} else {
print("Transaction successfully committed!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment