FIRDocumentSnapshot.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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::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. return FieldValueOptions(InternalServerTimestampBehavior(serverTimestampBehavior));
  175. }
  176. - (id)convertedValue:(FieldValue)value options:(const FieldValueOptions &)options {
  177. switch (value.type()) {
  178. case FieldValue::Type::Null:
  179. return [NSNull null];
  180. case FieldValue::Type::Boolean:
  181. return value.boolean_value() ? @YES : @NO;
  182. case FieldValue::Type::Integer:
  183. return @(value.integer_value());
  184. case FieldValue::Type::Double:
  185. return @(value.double_value());
  186. case FieldValue::Type::Timestamp:
  187. return [self convertedTimestamp:value];
  188. case FieldValue::Type::ServerTimestamp:
  189. return [self convertedServerTimestamp:value options:options];
  190. case FieldValue::Type::String:
  191. return util::MakeNSString(value.string_value());
  192. case FieldValue::Type::Blob:
  193. return MakeNSData(value.blob_value());
  194. case FieldValue::Type::Reference:
  195. return [self convertedReference:value];
  196. case FieldValue::Type::GeoPoint:
  197. return MakeFIRGeoPoint(value.geo_point_value());
  198. case FieldValue::Type::Array:
  199. return [self convertedArray:value.array_value() options:options];
  200. case FieldValue::Type::Object:
  201. return [self convertedObject:value.object_value() options:options];
  202. }
  203. UNREACHABLE();
  204. }
  205. - (id)convertedTimestamp:(const FieldValue &)value {
  206. return MakeFIRTimestamp(value.timestamp_value());
  207. }
  208. - (id)convertedServerTimestamp:(const FieldValue &)value
  209. options:(const FieldValueOptions &)options {
  210. const auto &sts = value.server_timestamp_value();
  211. switch (options.server_timestamp_behavior()) {
  212. case ServerTimestampBehavior::kNone:
  213. return [NSNull null];
  214. case ServerTimestampBehavior::kEstimate: {
  215. FieldValue local_write_time = FieldValue::FromTimestamp(sts.local_write_time());
  216. return [self convertedTimestamp:local_write_time];
  217. }
  218. case ServerTimestampBehavior::kPrevious:
  219. return sts.previous_value() ? [self convertedValue:*sts.previous_value() options:options]
  220. : [NSNull null];
  221. }
  222. UNREACHABLE();
  223. }
  224. - (id)convertedReference:(const FieldValue &)value {
  225. const auto &ref = value.reference_value();
  226. const DatabaseId &refDatabase = ref.database_id();
  227. const DatabaseId &database = _snapshot.firestore()->database_id();
  228. if (refDatabase != database) {
  229. LOG_WARN("Document %s contains a document reference within a different database (%s/%s) which "
  230. "is not supported. It will be treated as a reference within the current database "
  231. "(%s/%s) instead.",
  232. _snapshot.CreateReference().Path(), refDatabase.project_id(),
  233. refDatabase.database_id(), database.project_id(), database.database_id());
  234. }
  235. const DocumentKey &key = ref.key();
  236. return [[FIRDocumentReference alloc] initWithKey:key firestore:_snapshot.firestore()];
  237. }
  238. - (NSArray<id> *)convertedArray:(const FieldValue::Array &)arrayContents
  239. options:(const FieldValueOptions &)options {
  240. NSMutableArray *result = [NSMutableArray arrayWithCapacity:arrayContents.size()];
  241. for (const FieldValue &value : arrayContents) {
  242. [result addObject:[self convertedValue:value options:options]];
  243. }
  244. return result;
  245. }
  246. - (NSDictionary<NSString *, id> *)convertedObject:(const FieldValue::Map &)objectValue
  247. options:(const FieldValueOptions &)options {
  248. NSMutableDictionary *result = [NSMutableDictionary dictionary];
  249. for (const auto &kv : objectValue) {
  250. const std::string &key = kv.first;
  251. const FieldValue &value = kv.second;
  252. result[util::MakeNSString(key)] = [self convertedValue:value options:options];
  253. }
  254. return result;
  255. }
  256. @end
  257. @implementation FIRQueryDocumentSnapshot
  258. - (NSDictionary<NSString *, id> *)data {
  259. NSDictionary<NSString *, id> *data = [super data];
  260. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  261. return data;
  262. }
  263. - (NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  264. (FIRServerTimestampBehavior)serverTimestampBehavior {
  265. NSDictionary<NSString *, id> *data =
  266. [super dataWithServerTimestampBehavior:serverTimestampBehavior];
  267. HARD_ASSERT(data, "Document in a QueryDocumentSnapshot should exist");
  268. return data;
  269. }
  270. @end
  271. NS_ASSUME_NONNULL_END