Firestore+AsyncAwait.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import FirebaseFirestore
  17. import Foundation
  18. #if compiler(>=5.5.2) && canImport(_Concurrency)
  19. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. public extension Firestore {
  21. /// Loads a Firestore bundle into the local cache.
  22. /// - Parameter bundleData: Data from the bundle to be loaded.
  23. /// - Throws: `Error` if the bundle data cannot be parsed.
  24. /// - Returns: The final `LoadBundleTaskProgress` that contains the total number of documents loaded.
  25. func loadBundle(_ bundleData: Data) async throws -> LoadBundleTaskProgress {
  26. return try await withCheckedThrowingContinuation { continuation in
  27. self.loadBundle(bundleData) { progress, error in
  28. if let err = error {
  29. continuation.resume(throwing: err)
  30. } else {
  31. // Our callbacks guarantee that we either return an error or a progress event.
  32. continuation.resume(returning: progress!)
  33. }
  34. }
  35. }
  36. }
  37. /// Loads a Firestore bundle into the local cache.
  38. /// - Parameter bundleStream: An input stream from which the bundle can be read.
  39. /// - Throws: `Error` if the bundle stream cannot be parsed.
  40. /// - Returns: The final `LoadBundleTaskProgress` that contains the total number of documents loaded.
  41. func loadBundle(_ bundleStream: InputStream) async throws -> LoadBundleTaskProgress {
  42. return try await withCheckedThrowingContinuation { continuation in
  43. self.loadBundle(bundleStream) { progress, error in
  44. if let err = error {
  45. continuation.resume(throwing: err)
  46. } else {
  47. // Our callbacks guarantee that we either return an error or a progress event.
  48. continuation.resume(returning: progress!)
  49. }
  50. }
  51. }
  52. }
  53. /// Executes the given updateBlock and then attempts to commit the changes applied within an atomic
  54. /// transaction.
  55. ///
  56. /// The maximum number of writes allowed in a single transaction is 500, but note that each usage of
  57. /// `FieldValue.serverTimestamp()`, `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or
  58. /// `FieldValue.increment()` inside a transaction counts as an additional write.
  59. ///
  60. /// In the `updateBlock`, a set of reads and writes can be performed atomically using the
  61. /// `Transaction` object passed to the block. After the `updateBlock` is run, Firestore will attempt
  62. /// to apply the changes to the server. If any of the data read has been modified outside of this
  63. /// transaction since being read, then the transaction will be retried by executing the `updateBlock`
  64. /// again. If the transaction still fails after 5 retries, then the transaction will fail.
  65. ///
  66. /// Since the `updateBlock` may be executed multiple times, it should avoiding doing anything that
  67. /// would cause side effects.
  68. ///
  69. /// Any value maybe be returned from the `updateBlock`. If the transaction is successfully committed,
  70. /// then the completion block will be passed that value. The `updateBlock` also has an `NSError` out
  71. /// parameter. If this is set, then the transaction will not attempt to commit, and the given error
  72. /// will be returned.
  73. ///
  74. /// The `Transaction` object passed to the `updateBlock` contains methods for accessing documents
  75. /// and collections. Unlike other firestore access, data accessed with the transaction will not
  76. /// reflect local changes that have not been committed. For this reason, it is required that all
  77. /// reads are performed before any writes. Transactions must be performed while online. Otherwise,
  78. /// reads will fail, the final commit will fail, and this function will return an error.
  79. ///
  80. /// - Parameter updateBlock The block to execute within the transaction context.
  81. /// - Throws Throws an error if the transaction could not be committed, or if an error was explicitly specified in the `updateBlock` parameter.
  82. /// - Returns Returns the value returned in the `updateBlock` parameter if no errors occurred.
  83. func runTransaction(_ updateBlock: @escaping (Transaction, NSErrorPointer)
  84. -> Any?) async throws -> Any? {
  85. // This needs to be wrapped in order to express a nullable return value upon success.
  86. // See https://github.com/firebase/firebase-ios-sdk/issues/9426 for more details.
  87. return try await withCheckedThrowingContinuation { continuation in
  88. self.runTransaction(updateBlock) { anyValue, error in
  89. if let err = error {
  90. continuation.resume(throwing: err)
  91. } else {
  92. continuation.resume(returning: anyValue)
  93. }
  94. }
  95. }
  96. }
  97. }
  98. #endif