FirestoreObjRefWrapper.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /*
  2. * Copyright 2023 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 FirebaseFirestore
  17. /// Property wrapper @FirestoreObjectReference,
  18. /// Indicates that the specified property value should be stored by reference instead of by value
  19. ///
  20. /// When loading a parent object, any references are not loaded by default and can be loaded on demand
  21. /// using the projected value of the wrapper.
  22. ///
  23. /// Structs that can be stored as a reference must implement the `ReferenceableObject` protocol
  24. ///
  25. /// Variables that are annotated with the propertyWrapper should be marked as `Optional` since they can be nil when not loaded or set
  26. ///
  27. /// Example:
  28. /// We have three structs representing a simplified UserProfile model -
  29. /// `UserProfile`
  30. /// `Employer` - an employer who the `UserProfile` works for
  31. /// `WorkLocation` - representing a generic location. This can be used to represent a generic location
  32. ///
  33. /// Since multiple Users can work for an Employer, it makes sense to have only one instance of an Employer that is referred to
  34. /// by multiple Users. Similarly multiple users can be in a WorkLocation. Additionally, an Employer can also be located
  35. /// in a WorkLocation (e.g. headquarters of an Employer). We can mark WorkLocation and Employer as a ReferenceableObjects.
  36. ///
  37. ///
  38. /// ```
  39. /// struct UserProfile: ReferenceableObject {
  40. /// var username: String
  41. ///
  42. /// @FirestoreObjectReference
  43. /// var employer: Employer?
  44. ///
  45. /// @FirestoreObjectReference
  46. /// var workLocation: WorkLocation?
  47. ///
  48. /// }
  49. ///
  50. /// struct Employer: ReferenceableObject {
  51. /// var name: String
  52. ///
  53. /// @FirestoreObjectReference
  54. /// var headquarters: WorkLocation?
  55. /// }
  56. ///
  57. /// struct WorkLocation: ReferenceableObject {
  58. /// var locationName: String
  59. /// var moreInfo: String
  60. ///
  61. /// }
  62. ///
  63. /// var userProfile = ...
  64. ///
  65. /// // use projected value to load referenced employer
  66. /// try await userProfile.$employer?.loadReferencedObject()
  67. ///
  68. /// // use projected value to load referenced workLocation
  69. /// try await prof.$workLocation?.loadReferencedObject()
  70. ///
  71. ///
  72. ///
  73. /// ```
  74. ///
  75. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  76. @propertyWrapper
  77. public struct FirestoreObjectReference<T> where T: ReferenceableObject {
  78. private var objectReference: ObjectReference<T>?
  79. public init(wrappedValue initialValue: T?) {
  80. updateInitialValue(initialValue: initialValue)
  81. }
  82. private mutating func updateInitialValue(initialValue: T?) {
  83. if let initialValue {
  84. let objId = initialValue.id ?? {
  85. let docRef = Firestore.firestore().collection(T.parentCollection()).document()
  86. return docRef.documentID
  87. }()
  88. objectReference = ObjectReference(
  89. objectId: objId,
  90. collection: T.parentCollection(),
  91. referencedObject: initialValue
  92. )
  93. }
  94. }
  95. public var wrappedValue: T? {
  96. get {
  97. return objectReference?.referencedObject
  98. }
  99. set {
  100. if objectReference != nil {
  101. objectReference?.referencedObject = newValue
  102. } else {
  103. updateInitialValue(initialValue: newValue)
  104. }
  105. }
  106. }
  107. public var projectedValue: ObjectReference<T>? {
  108. get {
  109. return objectReference
  110. }
  111. set {
  112. objectReference = newValue
  113. }
  114. }
  115. }
  116. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  117. extension FirestoreObjectReference: Codable {
  118. public init(from decoder: Decoder) throws {
  119. let container = try decoder.singleValueContainer()
  120. let objRef = try container.decode(ObjectReference<T>.self)
  121. objectReference = objRef
  122. }
  123. public func encode(to encoder: Encoder) throws {
  124. var container = encoder.singleValueContainer()
  125. if let objectReference {
  126. try container.encode(objectReference)
  127. if let value = objectReference.referencedObject {
  128. Task {
  129. try await ReferenceableObjectManager.instance.save(object: value)
  130. }
  131. }
  132. } else {
  133. try container.encodeNil()
  134. }
  135. }
  136. }