FIRDocumentSnapshot.mm 9.3 KB

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