FIRDocumentSnapshot.mm 9.1 KB

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