FIRDocumentSnapshot.mm 12 KB

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