DatabaseReference+WriteEncodable.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2020 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 Foundation
  17. #if SWIFT_PACKAGE
  18. @_exported import FirebaseDatabaseInternal
  19. #endif // SWIFT_PACKAGE
  20. import FirebaseSharedSwift
  21. public extension DatabaseReference {
  22. /// Encodes an instance of `Encodable` and overwrites the encoded data
  23. /// to the path referred by this `DatabaseReference`. If no value exists,
  24. /// it is created. If a value already exists, it is overwritten.
  25. ///
  26. /// See `Database.Encoder` for more details about the encoding process.
  27. ///
  28. /// - Parameters:
  29. /// - value: An instance of `Encodable` to be encoded to a document.
  30. /// - encoder: An encoder instance to use to run the encoding.
  31. /// - completion: A block to execute once the value has been successfully
  32. /// written to the server. This block will not be called while
  33. /// the client is offline, though local changes will be visible
  34. /// immediately.
  35. func setValue<T: Encodable>(from value: T,
  36. encoder: Database.Encoder = Database.Encoder(),
  37. completion: ((Error?) -> Void)? =
  38. nil) throws {
  39. let encoded = try encoder.encode(value)
  40. if let completion {
  41. setValue(encoded, withCompletionBlock: { error, _ in completion(error) })
  42. } else {
  43. setValue(encoded)
  44. }
  45. }
  46. }