FIRDocumentSnapshot.mm 11 KB

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