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