FIRDocumentSnapshot.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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
  53. hasPendingWrites:(BOOL)pendingWrites NS_DESIGNATED_INITIALIZER;
  54. - (const DocumentKey &)internalKey;
  55. @property(nonatomic, strong, readonly) FIRFirestore *firestore;
  56. @property(nonatomic, strong, readonly, nullable) FSTDocument *internalDocument;
  57. @property(nonatomic, assign, readonly) BOOL fromCache;
  58. @property(nonatomic, assign, readonly) BOOL pendingWrites;
  59. @end
  60. @implementation FIRDocumentSnapshot (Internal)
  61. + (instancetype)snapshotWithFirestore:(FIRFirestore *)firestore
  62. documentKey:(DocumentKey)documentKey
  63. document:(nullable FSTDocument *)document
  64. fromCache:(BOOL)fromCache
  65. hasPendingWrites:(BOOL)pendingWrites {
  66. return [[[self class] alloc] initWithFirestore:firestore
  67. documentKey:std::move(documentKey)
  68. document:document
  69. fromCache:fromCache
  70. hasPendingWrites:pendingWrites];
  71. }
  72. @end
  73. @implementation FIRDocumentSnapshot {
  74. FIRSnapshotMetadata *_cachedMetadata;
  75. DocumentKey _internalKey;
  76. }
  77. @dynamic metadata;
  78. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  79. documentKey:(DocumentKey)documentKey
  80. document:(nullable FSTDocument *)document
  81. fromCache:(BOOL)fromCache
  82. hasPendingWrites:(BOOL)pendingWrites {
  83. if (self = [super init]) {
  84. _firestore = firestore;
  85. _internalKey = std::move(documentKey);
  86. _internalDocument = document;
  87. _fromCache = fromCache;
  88. _pendingWrites = pendingWrites;
  89. }
  90. return self;
  91. }
  92. - (const DocumentKey &)internalKey {
  93. return _internalKey;
  94. }
  95. // NSObject Methods
  96. - (BOOL)isEqual:(nullable id)other {
  97. if (other == self) return YES;
  98. // self class could be FIRDocumentSnapshot or subtype. So we compare with base type explicitly.
  99. if (![other isKindOfClass:[FIRDocumentSnapshot class]]) return NO;
  100. return [self isEqualToSnapshot:other];
  101. }
  102. - (BOOL)isEqualToSnapshot:(nullable FIRDocumentSnapshot *)snapshot {
  103. if (self == snapshot) return YES;
  104. if (snapshot == nil) return NO;
  105. return [self.firestore isEqual:snapshot.firestore] && self.internalKey == snapshot.internalKey &&
  106. (self.internalDocument == snapshot.internalDocument ||
  107. [self.internalDocument isEqual:snapshot.internalDocument]) &&
  108. self.pendingWrites == snapshot.pendingWrites && self.fromCache == snapshot.fromCache;
  109. }
  110. - (NSUInteger)hash {
  111. NSUInteger hash = [self.firestore hash];
  112. hash = hash * 31u + self.internalKey.Hash();
  113. hash = hash * 31u + [self.internalDocument hash];
  114. hash = hash * 31u + (_pendingWrites ? 1 : 0);
  115. hash = hash * 31u + (self.fromCache ? 1 : 0);
  116. return hash;
  117. }
  118. @dynamic exists;
  119. - (BOOL)exists {
  120. return _internalDocument != nil;
  121. }
  122. - (FIRDocumentReference *)reference {
  123. return [FIRDocumentReference referenceWithKey:self.internalKey firestore:self.firestore];
  124. }
  125. - (NSString *)documentID {
  126. return util::WrapNSString(self.internalKey.path().last_segment());
  127. }
  128. - (FIRSnapshotMetadata *)metadata {
  129. if (!_cachedMetadata) {
  130. _cachedMetadata = [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:_pendingWrites
  131. fromCache:self.fromCache];
  132. }
  133. return _cachedMetadata;
  134. }
  135. - (nullable NSDictionary<NSString *, id> *)data {
  136. return [self dataWithServerTimestampBehavior:FIRServerTimestampBehaviorNone];
  137. }
  138. - (nullable NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  139. (FIRServerTimestampBehavior)serverTimestampBehavior {
  140. FSTFieldValueOptions *options = [self optionsForServerTimestampBehavior:serverTimestampBehavior];
  141. return self.internalDocument == nil
  142. ? nil
  143. : [self convertedObject:[self.internalDocument data] options:options];
  144. }
  145. - (nullable id)valueForField:(id)field {
  146. return [self valueForField:field serverTimestampBehavior:FIRServerTimestampBehaviorNone];
  147. }
  148. - (nullable id)valueForField:(id)field
  149. serverTimestampBehavior:(FIRServerTimestampBehavior)serverTimestampBehavior {
  150. FIRFieldPath *fieldPath;
  151. if ([field isKindOfClass:[NSString class]]) {
  152. fieldPath = [FIRFieldPath pathWithDotSeparatedString:field];
  153. } else if ([field isKindOfClass:[FIRFieldPath class]]) {
  154. fieldPath = field;
  155. } else {
  156. FSTThrowInvalidArgument(@"Subscript key must be an NSString or FIRFieldPath.");
  157. }
  158. FSTFieldValue *fieldValue = [[self.internalDocument data] valueForPath:fieldPath.internalValue];
  159. FSTFieldValueOptions *options = [self optionsForServerTimestampBehavior:serverTimestampBehavior];
  160. return fieldValue == nil ? nil : [self convertedValue:fieldValue options:options];
  161. }
  162. - (FSTFieldValueOptions *)optionsForServerTimestampBehavior:
  163. (FIRServerTimestampBehavior)serverTimestampBehavior {
  164. FSTServerTimestampBehavior internalBehavior =
  165. InternalServerTimestampBehavor(serverTimestampBehavior);
  166. #pragma clang diagnostic push
  167. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  168. return [[FSTFieldValueOptions alloc]
  169. initWithServerTimestampBehavior:internalBehavior
  170. timestampsInSnapshotsEnabled:self.firestore.settings.timestampsInSnapshotsEnabled];
  171. #pragma clang diagnostic pop
  172. }
  173. - (nullable id)objectForKeyedSubscript:(id)key {
  174. return [self valueForField:key];
  175. }
  176. - (id)convertedValue:(FSTFieldValue *)value options:(FSTFieldValueOptions *)options {
  177. if ([value isKindOfClass:[FSTObjectValue class]]) {
  178. return [self convertedObject:(FSTObjectValue *)value options:options];
  179. } else if ([value isKindOfClass:[FSTArrayValue class]]) {
  180. return [self convertedArray:(FSTArrayValue *)value options:options];
  181. } else if ([value isKindOfClass:[FSTReferenceValue class]]) {
  182. FSTReferenceValue *ref = (FSTReferenceValue *)value;
  183. const DatabaseId *refDatabase = ref.databaseID;
  184. const DatabaseId *database = self.firestore.databaseID;
  185. if (*refDatabase != *database) {
  186. // TODO(b/32073923): Log this as a proper warning.
  187. NSLog(@"WARNING: Document %@ contains a document reference within a different database "
  188. "(%s/%s) which is not supported. It will be treated as a reference within the "
  189. "current database (%s/%s) instead.",
  190. self.reference.path, refDatabase->project_id().c_str(),
  191. refDatabase->database_id().c_str(), database->project_id().c_str(),
  192. database->database_id().c_str());
  193. }
  194. DocumentKey key = [[ref valueWithOptions:options] key];
  195. return [FIRDocumentReference referenceWithKey:key firestore:self.firestore];
  196. } else {
  197. return [value valueWithOptions:options];
  198. }
  199. }
  200. - (NSDictionary<NSString *, id> *)convertedObject:(FSTObjectValue *)objectValue
  201. options:(FSTFieldValueOptions *)options {
  202. NSMutableDictionary *result = [NSMutableDictionary dictionary];
  203. [objectValue.internalValue
  204. enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *value, BOOL *stop) {
  205. result[key] = [self convertedValue:value options:options];
  206. }];
  207. return result;
  208. }
  209. - (NSArray<id> *)convertedArray:(FSTArrayValue *)arrayValue
  210. options:(FSTFieldValueOptions *)options {
  211. NSArray<FSTFieldValue *> *internalValue = arrayValue.internalValue;
  212. NSMutableArray *result = [NSMutableArray arrayWithCapacity:internalValue.count];
  213. [internalValue enumerateObjectsUsingBlock:^(id value, NSUInteger idx, BOOL *stop) {
  214. [result addObject:[self convertedValue:value options:options]];
  215. }];
  216. return result;
  217. }
  218. @end
  219. @interface FIRQueryDocumentSnapshot ()
  220. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  221. documentKey:(DocumentKey)documentKey
  222. document:(FSTDocument *)document
  223. fromCache:(BOOL)fromCache
  224. hasPendingWrites:(BOOL)pendingWrites NS_DESIGNATED_INITIALIZER;
  225. @end
  226. @implementation FIRQueryDocumentSnapshot
  227. - (instancetype)initWithFirestore:(FIRFirestore *)firestore
  228. documentKey:(DocumentKey)documentKey
  229. document:(FSTDocument *)document
  230. fromCache:(BOOL)fromCache
  231. hasPendingWrites:(BOOL)pendingWrites {
  232. self = [super initWithFirestore:firestore
  233. documentKey:std::move(documentKey)
  234. document:document
  235. fromCache:fromCache
  236. hasPendingWrites:pendingWrites];
  237. return self;
  238. }
  239. - (NSDictionary<NSString *, id> *)data {
  240. NSDictionary<NSString *, id> *data = [super data];
  241. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  242. return data;
  243. }
  244. - (NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  245. (FIRServerTimestampBehavior)serverTimestampBehavior {
  246. NSDictionary<NSString *, id> *data =
  247. [super dataWithServerTimestampBehavior:serverTimestampBehavior];
  248. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  249. return data;
  250. }
  251. @end
  252. NS_ASSUME_NONNULL_END