DocumentSnapshot+ReadDecodable.swift 1.8 KB

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