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