DocumentID.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. let documentRefUserInfoKey =
  19. CodingUserInfoKey(rawValue: "DocumentRefUserInfoKey")!
  20. /// A type that can initialize itself from a Firestore `DocumentReference`,
  21. /// which makes it suitable for use with the `@DocumentID` property wrapper.
  22. ///
  23. /// Firestore includes extensions that make `String` and `DocumentReference`
  24. /// conform to `DocumentIDWrappable`.
  25. ///
  26. /// Note that Firestore ignores fields annotated with `@DocumentID` when writing
  27. /// so there is no requirement to convert from the wrapped type back to a
  28. /// `DocumentReference`.
  29. public protocol DocumentIDWrappable {
  30. /// Creates a new instance by converting from the given `DocumentReference`.
  31. static func wrap(_ documentReference: DocumentReference) throws -> Self
  32. }
  33. extension String: DocumentIDWrappable {
  34. public static func wrap(_ documentReference: DocumentReference) throws -> Self {
  35. return documentReference.documentID
  36. }
  37. }
  38. extension DocumentReference: DocumentIDWrappable {
  39. public static func wrap(_ documentReference: DocumentReference) throws -> Self {
  40. // Swift complains that values of type DocumentReference cannot be returned
  41. // as Self which is nonsensical. The cast forces this to work.
  42. return documentReference as! Self
  43. }
  44. }
  45. /// An internal protocol that allows Firestore.Decoder to test if a type is a
  46. /// DocumentID of some kind without knowing the specific generic parameter that
  47. /// the user actually used.
  48. ///
  49. /// This is required because Swift does not define an existential type for all
  50. /// instances of a generic class--that is, it has no wildcard or raw type that
  51. /// matches a generic without any specific parameter. Swift does define an
  52. /// existential type for protocols though, so this protocol (to which DocumentID
  53. /// conforms) indirectly makes it possible to test for and act on any
  54. /// `DocumentID<Value>`.
  55. internal protocol DocumentIDProtocol {
  56. /// Initializes the DocumentID from a DocumentReference.
  57. init(from documentReference: DocumentReference?) throws
  58. }
  59. /// A value that is populated in Codable objects with the `DocumentReference`
  60. /// of the current document by the Firestore.Decoder when a document is read.
  61. ///
  62. /// If the field name used for this type conflicts with a read document field,
  63. /// an error is thrown. For example, if a custom object has a field `firstName`
  64. /// annotated with `@DocumentID`, and there is a property from the document
  65. /// named `firstName` as well, an error is thrown when you try to read the
  66. /// document.
  67. ///
  68. /// When writing a Codable object containing an `@DocumentID` annotated field,
  69. /// its value is ignored. This allows you to read a document from one path and
  70. /// write it into another without adjusting the value here.
  71. ///
  72. /// NOTE: Trying to encode/decode this type using encoders/decoders other than
  73. /// Firestore.Encoder leads to an error.
  74. @propertyWrapper
  75. public struct DocumentID<Value: DocumentIDWrappable & Codable>:
  76. DocumentIDProtocol, Codable, StructureCodingUncodedUnkeyed {
  77. var value: Value?
  78. public init(wrappedValue value: Value?) {
  79. self.value = value
  80. }
  81. public var wrappedValue: Value? {
  82. get { value }
  83. set { value = newValue }
  84. }
  85. // MARK: - `DocumentIDProtocol` conformance
  86. public init(from documentReference: DocumentReference?) throws {
  87. if let documentReference = documentReference {
  88. value = try Value.wrap(documentReference)
  89. } else {
  90. value = nil
  91. }
  92. }
  93. // MARK: - `Codable` implementation.
  94. public init(from decoder: Decoder) throws {
  95. guard let reference = decoder.userInfo[documentRefUserInfoKey] as? DocumentReference else {
  96. throw FirestoreDecodingError.decodingIsNotSupported(
  97. "Could not find DocumentReference for user info key: \(documentRefUserInfoKey)"
  98. )
  99. }
  100. try self.init(from: reference)
  101. }
  102. public func encode(to encoder: Encoder) throws {
  103. throw FirestoreEncodingError.encodingIsNotSupported(
  104. "DocumentID values can only be encoded with Firestore.Encoder"
  105. )
  106. }
  107. }
  108. extension DocumentID: Equatable where Value: Equatable {}
  109. extension DocumentID: Hashable where Value: Hashable {}