DocumentID.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /*
  2. * Copyright 2019 Google
  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. #if SWIFT_PACKAGE
  17. @_exported import FirebaseFirestoreInternalWrapper
  18. #else
  19. @_exported import FirebaseFirestoreInternal
  20. #endif // SWIFT_PACKAGE
  21. @_implementationOnly import FirebaseCoreExtension
  22. import FirebaseSharedSwift
  23. extension CodingUserInfoKey {
  24. static let documentRefUserInfoKey =
  25. CodingUserInfoKey(rawValue: "DocumentRefUserInfoKey")!
  26. }
  27. /// A type that can initialize itself from a Firestore `DocumentReference`,
  28. /// which makes it suitable for use with the `@DocumentID` property wrapper.
  29. ///
  30. /// Firestore includes extensions that make `String` and `DocumentReference`
  31. /// conform to `DocumentIDWrappable`.
  32. ///
  33. /// Note that Firestore ignores fields annotated with `@DocumentID` when writing
  34. /// so there is no requirement to convert from the wrapped type back to a
  35. /// `DocumentReference`.
  36. public protocol DocumentIDWrappable {
  37. /// Creates a new instance by converting from the given `DocumentReference`.
  38. static func wrap(_ documentReference: DocumentReference) throws -> Self
  39. }
  40. extension String: DocumentIDWrappable {
  41. public static func wrap(_ documentReference: DocumentReference) throws -> Self {
  42. return documentReference.documentID
  43. }
  44. }
  45. extension DocumentReference: DocumentIDWrappable {
  46. public static func wrap(_ documentReference: DocumentReference) throws -> Self {
  47. // Swift complains that values of type DocumentReference cannot be returned
  48. // as Self which is nonsensical. The cast forces this to work.
  49. return documentReference as! Self
  50. }
  51. }
  52. /// An internal protocol that allows Firestore.Decoder to test if a type is a
  53. /// DocumentID of some kind without knowing the specific generic parameter that
  54. /// the user actually used.
  55. ///
  56. /// This is required because Swift does not define an existential type for all
  57. /// instances of a generic class--that is, it has no wildcard or raw type that
  58. /// matches a generic without any specific parameter. Swift does define an
  59. /// existential type for protocols though, so this protocol (to which DocumentID
  60. /// conforms) indirectly makes it possible to test for and act on any
  61. /// `DocumentID<Value>`.
  62. protocol DocumentIDProtocol {
  63. /// Initializes the DocumentID from a DocumentReference.
  64. init(from documentReference: DocumentReference?) throws
  65. }
  66. /// A property wrapper type that marks a `DocumentReference?` or `String?` field to
  67. /// be populated with a document identifier when it is read.
  68. ///
  69. /// Apply the `@DocumentID` annotation to a `DocumentReference?` or `String?`
  70. /// property in a `Codable` object to have it populated with the document
  71. /// identifier when it is read and decoded from Firestore.
  72. ///
  73. /// - Important: The name of the property annotated with `@DocumentID` must not
  74. /// match the name of any fields in the Firestore document being read or else
  75. /// an error will be thrown. For example, if the `Codable` object has a
  76. /// property named `firstName` annotated with `@DocumentID`, and the Firestore
  77. /// document contains a field named `firstName`, an error will be thrown when
  78. /// attempting to decode the document.
  79. ///
  80. /// - Example Read:
  81. /// ````
  82. /// struct Player: Codable {
  83. /// @DocumentID var playerID: String?
  84. /// var health: Int64
  85. /// }
  86. ///
  87. /// let p = try! await Firestore.firestore()
  88. /// .collection("players")
  89. /// .document("player-1")
  90. /// .getDocument(as: Player.self)
  91. /// print("\(p.playerID!) Health: \(p.health)")
  92. ///
  93. /// // Prints: "Player: player-1, Health: 95"
  94. /// ````
  95. ///
  96. /// - Important: Trying to encode/decode this type using encoders/decoders other than
  97. /// Firestore.Encoder throws an error.
  98. ///
  99. /// - Important: When writing a Codable object containing an `@DocumentID` annotated field,
  100. /// its value is ignored. This allows you to read a document from one path and
  101. /// write it into another without adjusting the value here.
  102. @propertyWrapper
  103. public struct DocumentID<Value: DocumentIDWrappable & Codable>:
  104. StructureCodingUncodedUnkeyed {
  105. private var value: Value? = nil
  106. public init(wrappedValue value: Value?) {
  107. if let value {
  108. logIgnoredValueWarning(value: value)
  109. }
  110. self.value = value
  111. }
  112. public var wrappedValue: Value? {
  113. get { value }
  114. set { value = newValue }
  115. }
  116. private func logIgnoredValueWarning(value: Value) {
  117. FirebaseLogger.log(
  118. level: .warning,
  119. service: "[FirebaseFirestore]",
  120. code: "I-FST000002",
  121. message: """
  122. Attempting to initialize or set a @DocumentID property with a non-nil \
  123. value: "\(value)". The document ID is managed by Firestore and any \
  124. initialized or set value will be ignored. The ID is automatically set \
  125. when reading from Firestore.
  126. """
  127. )
  128. }
  129. }
  130. extension DocumentID: DocumentIDProtocol {
  131. init(from documentReference: DocumentReference?) throws {
  132. if let documentReference {
  133. value = try Value.wrap(documentReference)
  134. } else {
  135. value = nil
  136. }
  137. }
  138. }
  139. extension DocumentID: Codable {
  140. /// A `Codable` object containing an `@DocumentID` annotated field should
  141. /// only be decoded with `Firestore.Decoder`; this initializer throws if an
  142. /// unsupported decoder is used.
  143. ///
  144. /// - Parameter decoder: A decoder.
  145. /// - Throws: ``FirestoreDecodingError``
  146. public init(from decoder: Decoder) throws {
  147. guard let reference = decoder
  148. .userInfo[CodingUserInfoKey.documentRefUserInfoKey] as? DocumentReference else {
  149. throw FirestoreDecodingError.decodingIsNotSupported(
  150. """
  151. Could not find DocumentReference for user info key: \(CodingUserInfoKey
  152. .documentRefUserInfoKey).
  153. DocumentID values can only be decoded with Firestore.Decoder
  154. """
  155. )
  156. }
  157. try self.init(from: reference)
  158. }
  159. /// A `Codable` object containing an `@DocumentID` annotated field can only
  160. /// be encoded with `Firestore.Encoder`; this initializer always throws.
  161. ///
  162. /// - Parameter encoder: An invalid encoder.
  163. /// - Throws: ``FirestoreEncodingError``
  164. public func encode(to encoder: Encoder) throws {
  165. throw FirestoreEncodingError.encodingIsNotSupported(
  166. "DocumentID values can only be encoded with Firestore.Encoder"
  167. )
  168. }
  169. }
  170. extension DocumentID: Equatable where Value: Equatable {}
  171. extension DocumentID: Hashable where Value: Hashable {}