FIRDocumentSnapshot.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright 2017 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 "FIRDocumentSnapshot.h"
  17. #include <utility>
  18. #import "FIRFirestoreSettings.h"
  19. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  20. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  21. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  22. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  23. #import "Firestore/Source/Model/FSTDocument.h"
  24. #import "Firestore/Source/Model/FSTFieldValue.h"
  25. #import "Firestore/Source/Util/FSTUsageValidation.h"
  26. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  27. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  28. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  29. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  30. namespace util = firebase::firestore::util;
  31. using firebase::firestore::model::DatabaseId;
  32. using firebase::firestore::model::DocumentKey;
  33. NS_ASSUME_NONNULL_BEGIN
  34. /** Converts a public FIRServerTimestampBehavior into its internal equivalent. */
  35. static FSTServerTimestampBehavior InternalServerTimestampBehavor(
  36. FIRServerTimestampBehavior behavior) {
  37. switch (behavior) {
  38. case FIRServerTimestampBehaviorNone:
  39. return FSTServerTimestampBehaviorNone;
  40. case FIRServerTimestampBehaviorEstimate:
  41. return FSTServerTimestampBehaviorEstimate;
  42. case FIRServerTimestampBehaviorPrevious:
  43. return FSTServerTimestampBehaviorPrevious;
  44. default:
  45. HARD_FAIL("Unexpected server timestamp option: %s", behavior);
  46. }
  47. }
  48. @interface FIRDocumentSnapshot ()
  49. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  50. documentKey:(DocumentKey)documentKey
  51. document:(nullable FSTDocument *)document
  52. fromCache:(BOOL)fromCache NS_DESIGNATED_INITIALIZER;
  53. - (const DocumentKey &)internalKey;
  54. @property(nonatomic, strong, readonly) FIRFirestore *firestore;
  55. @property(nonatomic, strong, readonly, nullable) FSTDocument *internalDocument;
  56. @property(nonatomic, assign, readonly) BOOL fromCache;
  57. @end
  58. @implementation FIRDocumentSnapshot (Internal)
  59. + (instancetype)snapshotWithFirestore:(FIRFirestore *)firestore
  60. documentKey:(DocumentKey)documentKey
  61. document:(nullable FSTDocument *)document
  62. fromCache:(BOOL)fromCache {
  63. return [[[self class] alloc] initWithFirestore:firestore
  64. documentKey:std::move(documentKey)
  65. document:document
  66. fromCache:fromCache];
  67. }
  68. @end
  69. @implementation FIRDocumentSnapshot {
  70. FIRSnapshotMetadata *_cachedMetadata;
  71. DocumentKey _internalKey;
  72. }
  73. @dynamic metadata;
  74. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  75. documentKey:(DocumentKey)documentKey
  76. document:(nullable FSTDocument *)document
  77. fromCache:(BOOL)fromCache {
  78. if (self = [super init]) {
  79. _firestore = firestore;
  80. _internalKey = std::move(documentKey);
  81. _internalDocument = document;
  82. _fromCache = fromCache;
  83. }
  84. return self;
  85. }
  86. - (const DocumentKey &)internalKey {
  87. return _internalKey;
  88. }
  89. // NSObject Methods
  90. - (BOOL)isEqual:(nullable id)other {
  91. if (other == self) return YES;
  92. // self class could be FIRDocumentSnapshot or subtype. So we compare with base type explicitly.
  93. if (![other isKindOfClass:[FIRDocumentSnapshot class]]) return NO;
  94. return [self isEqualToSnapshot:other];
  95. }
  96. - (BOOL)isEqualToSnapshot:(nullable FIRDocumentSnapshot *)snapshot {
  97. if (self == snapshot) return YES;
  98. if (snapshot == nil) return NO;
  99. return [self.firestore isEqual:snapshot.firestore] && self.internalKey == snapshot.internalKey &&
  100. (self.internalDocument == snapshot.internalDocument ||
  101. [self.internalDocument isEqual:snapshot.internalDocument]) &&
  102. self.fromCache == snapshot.fromCache;
  103. }
  104. - (NSUInteger)hash {
  105. NSUInteger hash = [self.firestore hash];
  106. hash = hash * 31u + self.internalKey.Hash();
  107. hash = hash * 31u + [self.internalDocument hash];
  108. hash = hash * 31u + (self.fromCache ? 1 : 0);
  109. return hash;
  110. }
  111. @dynamic exists;
  112. - (BOOL)exists {
  113. return _internalDocument != nil;
  114. }
  115. - (FIRDocumentReference *)reference {
  116. return [FIRDocumentReference referenceWithKey:self.internalKey firestore:self.firestore];
  117. }
  118. - (NSString *)documentID {
  119. return util::WrapNSString(self.internalKey.path().last_segment());
  120. }
  121. - (FIRSnapshotMetadata *)metadata {
  122. if (!_cachedMetadata) {
  123. _cachedMetadata = [FIRSnapshotMetadata
  124. snapshotMetadataWithPendingWrites:self.internalDocument.hasLocalMutations
  125. fromCache:self.fromCache];
  126. }
  127. return _cachedMetadata;
  128. }
  129. - (nullable NSDictionary<NSString *, id> *)data {
  130. return [self dataWithServerTimestampBehavior:FIRServerTimestampBehaviorNone];
  131. }
  132. - (nullable NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  133. (FIRServerTimestampBehavior)serverTimestampBehavior {
  134. FSTFieldValueOptions *options = [self optionsForServerTimestampBehavior:serverTimestampBehavior];
  135. return self.internalDocument == nil
  136. ? nil
  137. : [self convertedObject:[self.internalDocument data] options:options];
  138. }
  139. - (nullable id)valueForField:(id)field {
  140. return [self valueForField:field serverTimestampBehavior:FIRServerTimestampBehaviorNone];
  141. }
  142. - (nullable id)valueForField:(id)field
  143. serverTimestampBehavior:(FIRServerTimestampBehavior)serverTimestampBehavior {
  144. FIRFieldPath *fieldPath;
  145. if ([field isKindOfClass:[NSString class]]) {
  146. fieldPath = [FIRFieldPath pathWithDotSeparatedString:field];
  147. } else if ([field isKindOfClass:[FIRFieldPath class]]) {
  148. fieldPath = field;
  149. } else {
  150. FSTThrowInvalidArgument(@"Subscript key must be an NSString or FIRFieldPath.");
  151. }
  152. FSTFieldValue *fieldValue = [[self.internalDocument data] valueForPath:fieldPath.internalValue];
  153. FSTFieldValueOptions *options = [self optionsForServerTimestampBehavior:serverTimestampBehavior];
  154. return fieldValue == nil ? nil : [self convertedValue:fieldValue options:options];
  155. }
  156. - (FSTFieldValueOptions *)optionsForServerTimestampBehavior:
  157. (FIRServerTimestampBehavior)serverTimestampBehavior {
  158. FSTServerTimestampBehavior internalBehavior =
  159. InternalServerTimestampBehavor(serverTimestampBehavior);
  160. return [[FSTFieldValueOptions alloc]
  161. initWithServerTimestampBehavior:internalBehavior
  162. timestampsInSnapshotsEnabled:self.firestore.settings.timestampsInSnapshotsEnabled];
  163. }
  164. - (nullable id)objectForKeyedSubscript:(id)key {
  165. return [self valueForField:key];
  166. }
  167. - (id)convertedValue:(FSTFieldValue *)value options:(FSTFieldValueOptions *)options {
  168. if ([value isKindOfClass:[FSTObjectValue class]]) {
  169. return [self convertedObject:(FSTObjectValue *)value options:options];
  170. } else if ([value isKindOfClass:[FSTArrayValue class]]) {
  171. return [self convertedArray:(FSTArrayValue *)value options:options];
  172. } else if ([value isKindOfClass:[FSTReferenceValue class]]) {
  173. FSTReferenceValue *ref = (FSTReferenceValue *)value;
  174. const DatabaseId *refDatabase = ref.databaseID;
  175. const DatabaseId *database = self.firestore.databaseID;
  176. if (*refDatabase != *database) {
  177. // TODO(b/32073923): Log this as a proper warning.
  178. NSLog(
  179. @"WARNING: Document %@ contains a document reference within a different database "
  180. "(%s/%s) which is not supported. It will be treated as a reference within the "
  181. "current database (%s/%s) instead.",
  182. self.reference.path, refDatabase->project_id().c_str(),
  183. refDatabase->database_id().c_str(), database->project_id().c_str(),
  184. database->database_id().c_str());
  185. }
  186. return [FIRDocumentReference referenceWithKey:[ref valueWithOptions:options]
  187. firestore:self.firestore];
  188. } else {
  189. return [value valueWithOptions:options];
  190. }
  191. }
  192. - (NSDictionary<NSString *, id> *)convertedObject:(FSTObjectValue *)objectValue
  193. options:(FSTFieldValueOptions *)options {
  194. NSMutableDictionary *result = [NSMutableDictionary dictionary];
  195. [objectValue.internalValue
  196. enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *value, BOOL *stop) {
  197. result[key] = [self convertedValue:value options:options];
  198. }];
  199. return result;
  200. }
  201. - (NSArray<id> *)convertedArray:(FSTArrayValue *)arrayValue
  202. options:(FSTFieldValueOptions *)options {
  203. NSArray<FSTFieldValue *> *internalValue = arrayValue.internalValue;
  204. NSMutableArray *result = [NSMutableArray arrayWithCapacity:internalValue.count];
  205. [internalValue enumerateObjectsUsingBlock:^(id value, NSUInteger idx, BOOL *stop) {
  206. [result addObject:[self convertedValue:value options:options]];
  207. }];
  208. return result;
  209. }
  210. @end
  211. @interface FIRQueryDocumentSnapshot ()
  212. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  213. documentKey:(DocumentKey)documentKey
  214. document:(FSTDocument *)document
  215. fromCache:(BOOL)fromCache NS_DESIGNATED_INITIALIZER;
  216. @end
  217. @implementation FIRQueryDocumentSnapshot
  218. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  219. documentKey:(DocumentKey)documentKey
  220. document:(FSTDocument *)document
  221. fromCache:(BOOL)fromCache {
  222. self = [super initWithFirestore:firestore
  223. documentKey:std::move(documentKey)
  224. document:document
  225. fromCache:fromCache];
  226. return self;
  227. }
  228. - (NSDictionary<NSString *, id> *)data {
  229. NSDictionary<NSString *, id> *data = [super data];
  230. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  231. return data;
  232. }
  233. - (NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  234. (FIRServerTimestampBehavior)serverTimestampBehavior {
  235. NSDictionary<NSString *, id> *data =
  236. [super dataWithServerTimestampBehavior:serverTimestampBehavior];
  237. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  238. return data;
  239. }
  240. @end
  241. NS_ASSUME_NONNULL_END