FIRDocumentSnapshot.mm 12 KB

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