DocumentID.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 = value {
  108. logIgnoredValueWarning(value: value)
  109. }
  110. self.value = value
  111. }
  112. public var wrappedValue: Value? {
  113. get { value }
  114. set {
  115. if let someNewValue = newValue {
  116. logIgnoredValueWarning(value: someNewValue)
  117. }
  118. value = newValue
  119. }
  120. }
  121. private func logIgnoredValueWarning(value: Value) {
  122. FirebaseLogger.log(
  123. level: .warning,
  124. service: "[FirebaseFirestoreSwift]",
  125. code: "I-FST000002",
  126. message: """
  127. Attempting to initialize or set a @DocumentID property with a non-nil \
  128. value: "\(value)". The document ID is managed by Firestore and any \
  129. initialized or set value will be ignored. The ID is automatically set \
  130. when reading from Firestore.
  131. """
  132. )
  133. }
  134. }
  135. extension DocumentID: DocumentIDProtocol {
  136. init(from documentReference: DocumentReference?) throws {
  137. if let documentReference = documentReference {
  138. value = try Value.wrap(documentReference)
  139. } else {
  140. value = nil
  141. }
  142. }
  143. }
  144. extension DocumentID: Codable {
  145. /// A `Codable` object containing an `@DocumentID` annotated field should
  146. /// only be decoded with `Firestore.Decoder`; this initializer throws if an
  147. /// unsupported decoder is used.
  148. ///
  149. /// - Parameter decoder: A decoder.
  150. /// - Throws: ``FirestoreDecodingError``
  151. public init(from decoder: Decoder) throws {
  152. guard let reference = decoder
  153. .userInfo[CodingUserInfoKey.documentRefUserInfoKey] as? DocumentReference else {
  154. throw FirestoreDecodingError.decodingIsNotSupported(
  155. """
  156. Could not find DocumentReference for user info key: \(CodingUserInfoKey
  157. .documentRefUserInfoKey).
  158. DocumentID values can only be decoded with Firestore.Decoder
  159. """
  160. )
  161. }
  162. try self.init(from: reference)
  163. }
  164. /// A `Codable` object containing an `@DocumentID` annotated field can only
  165. /// be encoded with `Firestore.Encoder`; this initializer always throws.
  166. ///
  167. /// - Parameter encoder: An invalid encoder.
  168. /// - Throws: ``FirestoreEncodingError``
  169. public func encode(to encoder: Encoder) throws {
  170. throw FirestoreEncodingError.encodingIsNotSupported(
  171. "DocumentID values can only be encoded with Firestore.Encoder"
  172. )
  173. }
  174. }
  175. extension DocumentID: Equatable where Value: Equatable {}
  176. extension DocumentID: Hashable where Value: Hashable {}