DatabaseReference+WriteEncodable.swift 1.8 KB

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