FIRDocumentSnapshot.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 <vector>
  19. #include "Firestore/core/src/firebase/firestore/util/warnings.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/FIRGeoPoint+Internal.h"
  24. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  25. #import "Firestore/Source/API/FIRTimestamp+Internal.h"
  26. #import "Firestore/Source/API/converters.h"
  27. #import "Firestore/Source/Model/FSTDocument.h"
  28. #include "Firestore/core/src/firebase/firestore/api/document_snapshot.h"
  29. #include "Firestore/core/src/firebase/firestore/api/firestore.h"
  30. #include "Firestore/core/src/firebase/firestore/api/input_validation.h"
  31. #include "Firestore/core/src/firebase/firestore/api/settings.h"
  32. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  33. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  34. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  35. #include "Firestore/core/src/firebase/firestore/model/field_value_options.h"
  36. #include "Firestore/core/src/firebase/firestore/nanopb/nanopb_util.h"
  37. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  38. #include "Firestore/core/src/firebase/firestore/util/log.h"
  39. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  40. namespace util = firebase::firestore::util;
  41. using firebase::Timestamp;
  42. using firebase::firestore::GeoPoint;
  43. using firebase::firestore::api::DocumentSnapshot;
  44. using firebase::firestore::api::Firestore;
  45. using firebase::firestore::api::MakeFIRGeoPoint;
  46. using firebase::firestore::api::MakeFIRTimestamp;
  47. using firebase::firestore::api::SnapshotMetadata;
  48. using firebase::firestore::api::ThrowInvalidArgument;
  49. using firebase::firestore::model::DatabaseId;
  50. using firebase::firestore::model::DocumentKey;
  51. using firebase::firestore::model::FieldValue;
  52. using firebase::firestore::model::FieldValueOptions;
  53. using firebase::firestore::model::ObjectValue;
  54. using firebase::firestore::model::ServerTimestampBehavior;
  55. using firebase::firestore::nanopb::MakeNSData;
  56. using firebase::firestore::util::WrapNSString;
  57. NS_ASSUME_NONNULL_BEGIN
  58. namespace {
  59. /**
  60. * Converts a public FIRServerTimestampBehavior into its internal equivalent.
  61. */
  62. ServerTimestampBehavior InternalServerTimestampBehavior(FIRServerTimestampBehavior behavior) {
  63. switch (behavior) {
  64. case FIRServerTimestampBehaviorNone:
  65. return ServerTimestampBehavior::kNone;
  66. case FIRServerTimestampBehaviorEstimate:
  67. return ServerTimestampBehavior::kEstimate;
  68. case FIRServerTimestampBehaviorPrevious:
  69. return ServerTimestampBehavior::kPrevious;
  70. default:
  71. HARD_FAIL("Unexpected server timestamp option: %s", behavior);
  72. }
  73. }
  74. } // namespace
  75. @implementation FIRDocumentSnapshot {
  76. DocumentSnapshot _snapshot;
  77. FIRSnapshotMetadata *_cachedMetadata;
  78. }
  79. - (instancetype)initWithSnapshot:(DocumentSnapshot &&)snapshot {
  80. if (self = [super init]) {
  81. _snapshot = std::move(snapshot);
  82. }
  83. return self;
  84. }
  85. - (instancetype)initWithFirestore:(std::shared_ptr<Firestore>)firestore
  86. documentKey:(DocumentKey)documentKey
  87. document:(nullable FSTDocument *)document
  88. metadata:(SnapshotMetadata)metadata {
  89. DocumentSnapshot wrapped{firestore, std::move(documentKey), document, std::move(metadata)};
  90. return [self initWithSnapshot:std::move(wrapped)];
  91. }
  92. - (instancetype)initWithFirestore:(std::shared_ptr<Firestore>)firestore
  93. documentKey:(DocumentKey)documentKey
  94. document:(nullable FSTDocument *)document
  95. fromCache:(bool)fromCache
  96. hasPendingWrites:(bool)hasPendingWrites {
  97. return [self initWithFirestore:firestore
  98. documentKey:std::move(documentKey)
  99. document:document
  100. metadata:SnapshotMetadata(hasPendingWrites, fromCache)];
  101. }
  102. // NSObject Methods
  103. - (BOOL)isEqual:(nullable id)other {
  104. if (other == self) return YES;
  105. // self class could be FIRDocumentSnapshot or subtype. So we compare with base type explicitly.
  106. if (![other isKindOfClass:[FIRDocumentSnapshot class]]) return NO;
  107. return _snapshot == static_cast<FIRDocumentSnapshot *>(other)->_snapshot;
  108. }
  109. - (NSUInteger)hash {
  110. return _snapshot.Hash();
  111. }
  112. @dynamic exists;
  113. - (BOOL)exists {
  114. return _snapshot.exists();
  115. }
  116. - (nullable FSTDocument *)internalDocument {
  117. return _snapshot.internal_document();
  118. }
  119. - (FIRDocumentReference *)reference {
  120. return [[FIRDocumentReference alloc] initWithReference:_snapshot.CreateReference()];
  121. }
  122. - (NSString *)documentID {
  123. return WrapNSString(_snapshot.document_id());
  124. }
  125. @dynamic metadata;
  126. - (FIRSnapshotMetadata *)metadata {
  127. if (!_cachedMetadata) {
  128. _cachedMetadata = [[FIRSnapshotMetadata alloc] initWithMetadata:_snapshot.metadata()];
  129. }
  130. return _cachedMetadata;
  131. }
  132. - (nullable NSDictionary<NSString *, id> *)data {
  133. return [self dataWithServerTimestampBehavior:FIRServerTimestampBehaviorNone];
  134. }
  135. - (nullable NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  136. (FIRServerTimestampBehavior)serverTimestampBehavior {
  137. FieldValueOptions options = [self optionsForServerTimestampBehavior:serverTimestampBehavior];
  138. absl::optional<ObjectValue> data = _snapshot.GetData();
  139. if (!data) return nil;
  140. return [self convertedObject:data->GetInternalValue() options:options];
  141. }
  142. - (nullable id)valueForField:(id)field {
  143. return [self valueForField:field serverTimestampBehavior:FIRServerTimestampBehaviorNone];
  144. }
  145. - (nullable id)valueForField:(id)field
  146. serverTimestampBehavior:(FIRServerTimestampBehavior)serverTimestampBehavior {
  147. FIRFieldPath *fieldPath;
  148. if ([field isKindOfClass:[NSString class]]) {
  149. fieldPath = [FIRFieldPath pathWithDotSeparatedString:field];
  150. } else if ([field isKindOfClass:[FIRFieldPath class]]) {
  151. fieldPath = field;
  152. } else {
  153. ThrowInvalidArgument("Subscript key must be an NSString or FIRFieldPath.");
  154. }
  155. absl::optional<FieldValue> fieldValue = _snapshot.GetValue(fieldPath.internalValue);
  156. FieldValueOptions options = [self optionsForServerTimestampBehavior:serverTimestampBehavior];
  157. return !fieldValue ? nil : [self convertedValue:*fieldValue options:options];
  158. }
  159. - (nullable id)objectForKeyedSubscript:(id)key {
  160. return [self valueForField:key];
  161. }
  162. - (FieldValueOptions)optionsForServerTimestampBehavior:
  163. (FIRServerTimestampBehavior)serverTimestampBehavior {
  164. SUPPRESS_DEPRECATED_DECLARATIONS_BEGIN()
  165. return FieldValueOptions(InternalServerTimestampBehavior(serverTimestampBehavior),
  166. _snapshot.firestore()->settings().timestamps_in_snapshots_enabled());
  167. SUPPRESS_END()
  168. }
  169. - (id)convertedValue:(FieldValue)value options:(const FieldValueOptions &)options {
  170. switch (value.type()) {
  171. case FieldValue::Type::Null:
  172. return [NSNull null];
  173. case FieldValue::Type::Boolean:
  174. return value.boolean_value() ? @YES : @NO;
  175. case FieldValue::Type::Integer:
  176. return @(value.integer_value());
  177. case FieldValue::Type::Double:
  178. return @(value.double_value());
  179. case FieldValue::Type::Timestamp:
  180. return [self convertedTimestamp:value options:options];
  181. case FieldValue::Type::ServerTimestamp:
  182. return [self convertedServerTimestamp:value options:options];
  183. case FieldValue::Type::String:
  184. return util::WrapNSString(value.string_value());
  185. case FieldValue::Type::Blob:
  186. return MakeNSData(value.blob_value());
  187. case FieldValue::Type::Reference:
  188. return [self convertedReference:value];
  189. case FieldValue::Type::GeoPoint:
  190. return MakeFIRGeoPoint(value.geo_point_value());
  191. case FieldValue::Type::Array:
  192. return [self convertedArray:value.array_value() options:options];
  193. case FieldValue::Type::Object:
  194. return [self convertedObject:value.object_value() options:options];
  195. }
  196. UNREACHABLE();
  197. }
  198. - (id)convertedTimestamp:(const FieldValue &)value options:(const FieldValueOptions &)options {
  199. FIRTimestamp *wrapped = MakeFIRTimestamp(value.timestamp_value());
  200. if (options.timestamps_in_snapshots_enabled()) {
  201. return wrapped;
  202. } else {
  203. return [wrapped dateValue];
  204. }
  205. }
  206. - (id)convertedServerTimestamp:(const FieldValue &)value
  207. options:(const FieldValueOptions &)options {
  208. const auto &sts = value.server_timestamp_value();
  209. switch (options.server_timestamp_behavior()) {
  210. case ServerTimestampBehavior::kNone:
  211. return [NSNull null];
  212. case ServerTimestampBehavior::kEstimate: {
  213. FieldValue local_write_time = FieldValue::FromTimestamp(sts.local_write_time());
  214. return [self convertedTimestamp:local_write_time options:options];
  215. }
  216. case ServerTimestampBehavior::kPrevious:
  217. return sts.previous_value() ? [self convertedValue:*sts.previous_value() options:options]
  218. : [NSNull null];
  219. }
  220. UNREACHABLE();
  221. }
  222. - (id)convertedReference:(const FieldValue &)value {
  223. const auto &ref = value.reference_value();
  224. const DatabaseId &refDatabase = ref.database_id();
  225. const DatabaseId &database = _snapshot.firestore()->database_id();
  226. if (refDatabase != database) {
  227. LOG_WARN("Document %s contains a document reference within a different database (%s/%s) which "
  228. "is not supported. It will be treated as a reference within the current database "
  229. "(%s/%s) instead.",
  230. _snapshot.CreateReference().Path(), refDatabase.project_id(),
  231. refDatabase.database_id(), database.project_id(), database.database_id());
  232. }
  233. const DocumentKey &key = ref.key();
  234. return [[FIRDocumentReference alloc] initWithKey:key firestore:_snapshot.firestore()];
  235. }
  236. - (NSArray<id> *)convertedArray:(const FieldValue::Array &)arrayContents
  237. options:(const FieldValueOptions &)options {
  238. NSMutableArray *result = [NSMutableArray arrayWithCapacity:arrayContents.size()];
  239. for (const FieldValue &value : arrayContents) {
  240. [result addObject:[self convertedValue:value options:options]];
  241. }
  242. return result;
  243. }
  244. - (NSDictionary<NSString *, id> *)convertedObject:(const FieldValue::Map &)objectValue
  245. options:(const FieldValueOptions &)options {
  246. NSMutableDictionary *result = [NSMutableDictionary dictionary];
  247. for (const auto &kv : objectValue) {
  248. const std::string &key = kv.first;
  249. const FieldValue &value = kv.second;
  250. result[util::WrapNSString(key)] = [self convertedValue:value options:options];
  251. }
  252. return result;
  253. }
  254. @end
  255. @implementation FIRQueryDocumentSnapshot
  256. - (NSDictionary<NSString *, id> *)data {
  257. NSDictionary<NSString *, id> *data = [super data];
  258. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  259. return data;
  260. }
  261. - (NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  262. (FIRServerTimestampBehavior)serverTimestampBehavior {
  263. NSDictionary<NSString *, id> *data =
  264. [super dataWithServerTimestampBehavior:serverTimestampBehavior];
  265. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  266. return data;
  267. }
  268. @end
  269. NS_ASSUME_NONNULL_END