FIRDocumentSnapshot.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * Copyright 2017 Google LLC
  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/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/api/document_reference.h"
  28. #include "Firestore/core/src/api/document_snapshot.h"
  29. #include "Firestore/core/src/api/firestore.h"
  30. #include "Firestore/core/src/api/settings.h"
  31. #include "Firestore/core/src/model/database_id.h"
  32. #include "Firestore/core/src/model/document_key.h"
  33. #include "Firestore/core/src/model/field_path.h"
  34. #include "Firestore/core/src/model/field_value.h"
  35. #include "Firestore/core/src/model/field_value_options.h"
  36. #include "Firestore/core/src/nanopb/nanopb_util.h"
  37. #include "Firestore/core/src/util/exception.h"
  38. #include "Firestore/core/src/util/hard_assert.h"
  39. #include "Firestore/core/src/util/log.h"
  40. #include "Firestore/core/src/util/string_apple.h"
  41. namespace util = firebase::firestore::util;
  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. return FieldValueOptions(InternalServerTimestampBehavior(serverTimestampBehavior));
  173. }
  174. - (id)convertedValue:(FieldValue)value options:(const FieldValueOptions &)options {
  175. switch (value.type()) {
  176. case FieldValue::Type::Null:
  177. return [NSNull null];
  178. case FieldValue::Type::Boolean:
  179. return value.boolean_value() ? @YES : @NO;
  180. case FieldValue::Type::Integer:
  181. return @(value.integer_value());
  182. case FieldValue::Type::Double:
  183. return @(value.double_value());
  184. case FieldValue::Type::Timestamp:
  185. return [self convertedTimestamp:value];
  186. case FieldValue::Type::ServerTimestamp:
  187. return [self convertedServerTimestamp:value options:options];
  188. case FieldValue::Type::String:
  189. return util::MakeNSString(value.string_value());
  190. case FieldValue::Type::Blob:
  191. return MakeNSData(value.blob_value());
  192. case FieldValue::Type::Reference:
  193. return [self convertedReference:value];
  194. case FieldValue::Type::GeoPoint:
  195. return MakeFIRGeoPoint(value.geo_point_value());
  196. case FieldValue::Type::Array:
  197. return [self convertedArray:value.array_value() options:options];
  198. case FieldValue::Type::Object:
  199. return [self convertedObject:value.object_value() options:options];
  200. }
  201. UNREACHABLE();
  202. }
  203. - (id)convertedTimestamp:(const FieldValue &)value {
  204. return MakeFIRTimestamp(value.timestamp_value());
  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];
  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::MakeNSString(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