FIRDocumentReference.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 "FIRDocumentReference.h"
  17. #include <memory>
  18. #include <utility>
  19. #import "FIRFirestoreErrors.h"
  20. #import "FIRFirestoreSource.h"
  21. #import "FIRSnapshotMetadata.h"
  22. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  23. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  24. #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
  25. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  26. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  27. #import "Firestore/Source/API/FSTUserDataConverter.h"
  28. #import "Firestore/Source/Core/FSTEventManager.h"
  29. #import "Firestore/Source/Core/FSTFirestoreClient.h"
  30. #import "Firestore/Source/Core/FSTQuery.h"
  31. #import "Firestore/Source/Model/FSTDocumentSet.h"
  32. #import "Firestore/Source/Model/FSTFieldValue.h"
  33. #import "Firestore/Source/Model/FSTMutation.h"
  34. #import "Firestore/Source/Util/FSTAsyncQueryListener.h"
  35. #import "Firestore/Source/Util/FSTUsageValidation.h"
  36. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  37. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  38. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  39. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  40. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  41. namespace util = firebase::firestore::util;
  42. using firebase::firestore::core::ParsedSetData;
  43. using firebase::firestore::core::ParsedUpdateData;
  44. using firebase::firestore::model::DocumentKey;
  45. using firebase::firestore::model::Precondition;
  46. using firebase::firestore::model::ResourcePath;
  47. NS_ASSUME_NONNULL_BEGIN
  48. #pragma mark - FIRDocumentReference
  49. @interface FIRDocumentReference ()
  50. - (instancetype)initWithKey:(DocumentKey)key
  51. firestore:(FIRFirestore *)firestore NS_DESIGNATED_INITIALIZER;
  52. @end
  53. @implementation FIRDocumentReference {
  54. DocumentKey _key;
  55. }
  56. - (instancetype)initWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  57. if (self = [super init]) {
  58. _key = std::move(key);
  59. _firestore = firestore;
  60. }
  61. return self;
  62. }
  63. #pragma mark - NSObject Methods
  64. - (BOOL)isEqual:(nullable id)other {
  65. if (other == self) return YES;
  66. if (![[other class] isEqual:[self class]]) return NO;
  67. return [self isEqualToReference:other];
  68. }
  69. - (BOOL)isEqualToReference:(nullable FIRDocumentReference *)reference {
  70. if (self == reference) return YES;
  71. if (reference == nil) return NO;
  72. return [self.firestore isEqual:reference.firestore] && self.key == reference.key;
  73. }
  74. - (NSUInteger)hash {
  75. NSUInteger hash = [self.firestore hash];
  76. hash = hash * 31u + self.key.Hash();
  77. return hash;
  78. }
  79. #pragma mark - Public Methods
  80. - (NSString *)documentID {
  81. return util::WrapNSString(self.key.path().last_segment());
  82. }
  83. - (FIRCollectionReference *)parent {
  84. return [FIRCollectionReference referenceWithPath:self.key.path().PopLast()
  85. firestore:self.firestore];
  86. }
  87. - (NSString *)path {
  88. return util::WrapNSString(self.key.path().CanonicalString());
  89. }
  90. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  91. if (!collectionPath) {
  92. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  93. }
  94. const ResourcePath subPath = ResourcePath::FromString(util::MakeString(collectionPath));
  95. const ResourcePath path = self.key.path().Append(subPath);
  96. return [FIRCollectionReference referenceWithPath:path firestore:self.firestore];
  97. }
  98. - (void)setData:(NSDictionary<NSString *, id> *)documentData {
  99. return [self setData:documentData merge:NO completion:nil];
  100. }
  101. - (void)setData:(NSDictionary<NSString *, id> *)documentData merge:(BOOL)merge {
  102. return [self setData:documentData merge:merge completion:nil];
  103. }
  104. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  105. mergeFields:(NSArray<id> *)mergeFields {
  106. return [self setData:documentData mergeFields:mergeFields completion:nil];
  107. }
  108. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  109. completion:(nullable void (^)(NSError *_Nullable error))completion {
  110. return [self setData:documentData merge:NO completion:completion];
  111. }
  112. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  113. merge:(BOOL)merge
  114. completion:(nullable void (^)(NSError *_Nullable error))completion {
  115. ParsedSetData parsed = merge ? [self.firestore.dataConverter parsedMergeData:documentData
  116. fieldMask:nil]
  117. : [self.firestore.dataConverter parsedSetData:documentData];
  118. return [self.firestore.client
  119. writeMutations:std::move(parsed).ToMutations(self.key, Precondition::None())
  120. completion:completion];
  121. }
  122. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  123. mergeFields:(NSArray<id> *)mergeFields
  124. completion:(nullable void (^)(NSError *_Nullable error))completion {
  125. ParsedSetData parsed = [self.firestore.dataConverter parsedMergeData:documentData
  126. fieldMask:mergeFields];
  127. return [self.firestore.client
  128. writeMutations:std::move(parsed).ToMutations(self.key, Precondition::None())
  129. completion:completion];
  130. }
  131. - (void)updateData:(NSDictionary<id, id> *)fields {
  132. return [self updateData:fields completion:nil];
  133. }
  134. - (void)updateData:(NSDictionary<id, id> *)fields
  135. completion:(nullable void (^)(NSError *_Nullable error))completion {
  136. ParsedUpdateData parsed = [self.firestore.dataConverter parsedUpdateData:fields];
  137. return [self.firestore.client
  138. writeMutations:std::move(parsed).ToMutations(self.key, Precondition::Exists(true))
  139. completion:completion];
  140. }
  141. - (void)deleteDocument {
  142. return [self deleteDocumentWithCompletion:nil];
  143. }
  144. - (void)deleteDocumentWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  145. FSTDeleteMutation *mutation = [[FSTDeleteMutation alloc] initWithKey:self.key
  146. precondition:Precondition::None()];
  147. return [self.firestore.client writeMutations:@[ mutation ] completion:completion];
  148. }
  149. - (void)getDocumentWithCompletion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  150. NSError *_Nullable error))completion {
  151. return [self getDocumentWithSource:FIRFirestoreSourceDefault completion:completion];
  152. }
  153. - (void)getDocumentWithSource:(FIRFirestoreSource)source
  154. completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  155. NSError *_Nullable error))completion {
  156. if (source == FIRFirestoreSourceCache) {
  157. [self.firestore.client getDocumentFromLocalCache:self completion:completion];
  158. return;
  159. }
  160. FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  161. includeDocumentMetadataChanges:YES
  162. waitForSyncWhenOnline:YES];
  163. dispatch_semaphore_t registered = dispatch_semaphore_create(0);
  164. __block id<FIRListenerRegistration> listenerRegistration;
  165. FIRDocumentSnapshotBlock listener = ^(FIRDocumentSnapshot *snapshot, NSError *error) {
  166. if (error) {
  167. completion(nil, error);
  168. return;
  169. }
  170. // Remove query first before passing event to user to avoid user actions affecting the
  171. // now stale query.
  172. dispatch_semaphore_wait(registered, DISPATCH_TIME_FOREVER);
  173. [listenerRegistration remove];
  174. if (!snapshot.exists && snapshot.metadata.fromCache) {
  175. // TODO(dimond): Reconsider how to raise missing documents when offline.
  176. // If we're online and the document doesn't exist then we call the completion with
  177. // a document with document.exists set to false. If we're offline however, we call the
  178. // completion handler with an error. Two options:
  179. // 1) Cache the negative response from the server so we can deliver that even when you're
  180. // offline.
  181. // 2) Actually call the completion handler with an error if the document doesn't exist when
  182. // you are offline.
  183. completion(nil,
  184. [NSError errorWithDomain:FIRFirestoreErrorDomain
  185. code:FIRFirestoreErrorCodeUnavailable
  186. userInfo:@{
  187. NSLocalizedDescriptionKey :
  188. @"Failed to get document because the client is offline.",
  189. }]);
  190. } else if (snapshot.exists && snapshot.metadata.fromCache &&
  191. source == FIRFirestoreSourceServer) {
  192. completion(nil,
  193. [NSError errorWithDomain:FIRFirestoreErrorDomain
  194. code:FIRFirestoreErrorCodeUnavailable
  195. userInfo:@{
  196. NSLocalizedDescriptionKey :
  197. @"Failed to get document from server. (However, this "
  198. @"document does exist in the local cache. Run again "
  199. @"without setting source to FIRFirestoreSourceServer to "
  200. @"retrieve the cached document.)"
  201. }]);
  202. } else {
  203. completion(snapshot, nil);
  204. }
  205. };
  206. listenerRegistration = [self addSnapshotListenerInternalWithOptions:options listener:listener];
  207. dispatch_semaphore_signal(registered);
  208. }
  209. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRDocumentSnapshotBlock)listener {
  210. return [self addSnapshotListenerWithIncludeMetadataChanges:NO listener:listener];
  211. }
  212. - (id<FIRListenerRegistration>)
  213. addSnapshotListenerWithIncludeMetadataChanges:(BOOL)includeMetadataChanges
  214. listener:(FIRDocumentSnapshotBlock)listener {
  215. FSTListenOptions *options =
  216. [self internalOptionsForIncludeMetadataChanges:includeMetadataChanges];
  217. return [self addSnapshotListenerInternalWithOptions:options listener:listener];
  218. }
  219. - (id<FIRListenerRegistration>)
  220. addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
  221. listener:(FIRDocumentSnapshotBlock)listener {
  222. FIRFirestore *firestore = self.firestore;
  223. FSTQuery *query = [FSTQuery queryWithPath:self.key.path()];
  224. const DocumentKey key = self.key;
  225. FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
  226. if (error) {
  227. listener(nil, error);
  228. return;
  229. }
  230. HARD_ASSERT(snapshot.documents.count <= 1, "Too many document returned on a document query");
  231. FSTDocument *document = [snapshot.documents documentForKey:key];
  232. BOOL hasPendingWrites = document
  233. ? snapshot.mutatedKeys.contains(key)
  234. : NO; // We don't raise `hasPendingWrites` for deleted documents.
  235. FIRDocumentSnapshot *result = [FIRDocumentSnapshot snapshotWithFirestore:firestore
  236. documentKey:key
  237. document:document
  238. fromCache:snapshot.fromCache
  239. hasPendingWrites:hasPendingWrites];
  240. listener(result, nil);
  241. };
  242. FSTAsyncQueryListener *asyncListener =
  243. [[FSTAsyncQueryListener alloc] initWithExecutor:self.firestore.client.userExecutor
  244. snapshotHandler:snapshotHandler];
  245. FSTQueryListener *internalListener =
  246. [firestore.client listenToQuery:query
  247. options:internalOptions
  248. viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  249. return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
  250. asyncListener:asyncListener
  251. internalListener:internalListener];
  252. }
  253. /** Converts the public API options object to the internal options object. */
  254. - (FSTListenOptions *)internalOptionsForIncludeMetadataChanges:(BOOL)includeMetadataChanges {
  255. return [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:includeMetadataChanges
  256. includeDocumentMetadataChanges:includeMetadataChanges
  257. waitForSyncWhenOnline:NO];
  258. }
  259. @end
  260. #pragma mark - FIRDocumentReference (Internal)
  261. @implementation FIRDocumentReference (Internal)
  262. + (instancetype)referenceWithPath:(const ResourcePath &)path firestore:(FIRFirestore *)firestore {
  263. if (path.size() % 2 != 0) {
  264. FSTThrowInvalidArgument(@"Invalid document reference. Document references must have an even "
  265. "number of segments, but %s has %zu",
  266. path.CanonicalString().c_str(), path.size());
  267. }
  268. return [FIRDocumentReference referenceWithKey:DocumentKey{path} firestore:firestore];
  269. }
  270. + (instancetype)referenceWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  271. return [[FIRDocumentReference alloc] initWithKey:std::move(key) firestore:firestore];
  272. }
  273. - (const firebase::firestore::model::DocumentKey &)key {
  274. return _key;
  275. }
  276. @end
  277. NS_ASSUME_NONNULL_END