FIRDocumentReference.mm 12 KB

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