DocumentSnapshot+ReadDecodable.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright 2019 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 FirebaseFirestore
  18. extension DocumentSnapshot {
  19. /// Retrieves all fields in a document and converts them to an instance of
  20. /// caller-specified type. Returns `nil` if the document does not exist.
  21. ///
  22. /// By default, server-provided timestamps that have not yet been set to their
  23. /// final value will be returned as `NSNull`. Pass `serverTimestampBehavior`
  24. /// configure this behavior.
  25. ///
  26. /// See `Firestore.Decoder` for more details about the decoding process.
  27. ///
  28. /// - Parameters
  29. /// - type: The type to convert the document fields to.
  30. /// - serverTimestampBehavior: Configures how server timestamps that have
  31. /// not yet been set to their final value are returned from the snapshot.
  32. /// - decoder: The decoder to use to convert the document. `nil` to use
  33. /// default decoder.
  34. public func data<T: Decodable>(as type: T.Type,
  35. with serverTimestampBehavior: ServerTimestampBehavior = .none,
  36. decoder: Firestore.Decoder? = nil) throws -> T? {
  37. let d = decoder ?? Firestore.Decoder()
  38. if let data = data(with: serverTimestampBehavior) {
  39. return try d.decode(T.self, from: data, in: reference)
  40. }
  41. return nil
  42. }
  43. }