FIRDocumentReference.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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/FSTAsyncQueryListener.h"
  36. #import "Firestore/Source/Util/FSTUsageValidation.h"
  37. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  38. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  39. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  40. #include "Firestore/core/src/firebase/firestore/util/hard_assert.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. mergeFields:(NSArray<id> *)mergeFields {
  105. return [self setData:documentData mergeFields:mergeFields completion:nil];
  106. }
  107. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  108. completion:(nullable void (^)(NSError *_Nullable error))completion {
  109. return [self setData:documentData merge:NO completion:completion];
  110. }
  111. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  112. merge:(BOOL)merge
  113. completion:(nullable void (^)(NSError *_Nullable error))completion {
  114. FSTParsedSetData *parsed =
  115. merge ? [self.firestore.dataConverter parsedMergeData:documentData fieldMask:nil]
  116. : [self.firestore.dataConverter parsedSetData:documentData];
  117. return [self.firestore.client
  118. writeMutations:[parsed mutationsWithKey:self.key precondition:Precondition::None()]
  119. completion:completion];
  120. }
  121. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  122. mergeFields:(NSArray<id> *)mergeFields
  123. completion:(nullable void (^)(NSError *_Nullable error))completion {
  124. FSTParsedSetData *parsed =
  125. [self.firestore.dataConverter parsedMergeData:documentData fieldMask:mergeFields];
  126. return [self.firestore.client
  127. writeMutations:[parsed mutationsWithKey:self.key precondition:Precondition::None()]
  128. completion:completion];
  129. }
  130. - (void)updateData:(NSDictionary<id, id> *)fields {
  131. return [self updateData:fields completion:nil];
  132. }
  133. - (void)updateData:(NSDictionary<id, id> *)fields
  134. completion:(nullable void (^)(NSError *_Nullable error))completion {
  135. FSTParsedUpdateData *parsed = [self.firestore.dataConverter parsedUpdateData:fields];
  136. return [self.firestore.client
  137. writeMutations:[parsed mutationsWithKey:self.key precondition:Precondition::Exists(true)]
  138. completion:completion];
  139. }
  140. - (void)deleteDocument {
  141. return [self deleteDocumentWithCompletion:nil];
  142. }
  143. - (void)deleteDocumentWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  144. FSTDeleteMutation *mutation =
  145. [[FSTDeleteMutation alloc] initWithKey:self.key precondition:Precondition::None()];
  146. return [self.firestore.client writeMutations:@[ mutation ] completion:completion];
  147. }
  148. - (void)getDocumentWithCompletion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  149. NSError *_Nullable error))completion {
  150. return [self getDocumentWithSource:FIRFirestoreSourceDefault completion:completion];
  151. }
  152. - (void)getDocumentWithSource:(FIRFirestoreSource)source
  153. completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  154. NSError *_Nullable error))completion {
  155. if (source == FIRFirestoreSourceCache) {
  156. [self.firestore.client getDocumentFromLocalCache:self completion:completion];
  157. return;
  158. }
  159. FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  160. includeDocumentMetadataChanges:YES
  161. waitForSyncWhenOnline:YES];
  162. dispatch_semaphore_t registered = dispatch_semaphore_create(0);
  163. __block id<FIRListenerRegistration> listenerRegistration;
  164. FIRDocumentSnapshotBlock listener = ^(FIRDocumentSnapshot *snapshot, NSError *error) {
  165. if (error) {
  166. completion(nil, error);
  167. return;
  168. }
  169. // Remove query first before passing event to user to avoid user actions affecting the
  170. // now stale query.
  171. dispatch_semaphore_wait(registered, DISPATCH_TIME_FOREVER);
  172. [listenerRegistration remove];
  173. if (!snapshot.exists && snapshot.metadata.fromCache) {
  174. // TODO(dimond): Reconsider how to raise missing documents when offline.
  175. // If we're online and the document doesn't exist then we call the completion with
  176. // a document with document.exists set to false. If we're offline however, we call the
  177. // completion handler with an error. Two options:
  178. // 1) Cache the negative response from the server so we can deliver that even when you're
  179. // offline.
  180. // 2) Actually call the completion handler with an error if the document doesn't exist when
  181. // you are offline.
  182. completion(nil,
  183. [NSError errorWithDomain:FIRFirestoreErrorDomain
  184. code:FIRFirestoreErrorCodeUnavailable
  185. userInfo:@{
  186. NSLocalizedDescriptionKey :
  187. @"Failed to get document because the client is offline.",
  188. }]);
  189. } else if (snapshot.exists && snapshot.metadata.fromCache &&
  190. source == FIRFirestoreSourceServer) {
  191. completion(nil,
  192. [NSError errorWithDomain:FIRFirestoreErrorDomain
  193. code:FIRFirestoreErrorCodeUnavailable
  194. userInfo:@{
  195. NSLocalizedDescriptionKey :
  196. @"Failed to get document from server. (However, this "
  197. @"document does exist in the local cache. Run again "
  198. @"without setting source to FIRFirestoreSourceServer to "
  199. @"retrieve the cached document.)"
  200. }]);
  201. } else {
  202. completion(snapshot, nil);
  203. }
  204. };
  205. listenerRegistration = [self addSnapshotListenerInternalWithOptions:options listener:listener];
  206. dispatch_semaphore_signal(registered);
  207. }
  208. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRDocumentSnapshotBlock)listener {
  209. return [self addSnapshotListenerWithIncludeMetadataChanges:NO listener:listener];
  210. }
  211. - (id<FIRListenerRegistration>)
  212. addSnapshotListenerWithIncludeMetadataChanges:(BOOL)includeMetadataChanges
  213. listener:(FIRDocumentSnapshotBlock)listener {
  214. FSTListenOptions *options =
  215. [self internalOptionsForIncludeMetadataChanges:includeMetadataChanges];
  216. return [self addSnapshotListenerInternalWithOptions:options listener:listener];
  217. }
  218. - (id<FIRListenerRegistration>)
  219. addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
  220. listener:(FIRDocumentSnapshotBlock)listener {
  221. FIRFirestore *firestore = self.firestore;
  222. FSTQuery *query = [FSTQuery queryWithPath:self.key.path()];
  223. const DocumentKey key = self.key;
  224. FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
  225. if (error) {
  226. listener(nil, error);
  227. return;
  228. }
  229. HARD_ASSERT(snapshot.documents.count <= 1, "Too many document returned on a document query");
  230. FSTDocument *document = [snapshot.documents documentForKey:key];
  231. FIRDocumentSnapshot *result = [FIRDocumentSnapshot snapshotWithFirestore:firestore
  232. documentKey:key
  233. document:document
  234. fromCache:snapshot.fromCache];
  235. listener(result, nil);
  236. };
  237. FSTAsyncQueryListener *asyncListener =
  238. [[FSTAsyncQueryListener alloc] initWithExecutor:self.firestore.client.userExecutor
  239. snapshotHandler:snapshotHandler];
  240. FSTQueryListener *internalListener =
  241. [firestore.client listenToQuery:query
  242. options:internalOptions
  243. viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  244. return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
  245. asyncListener:asyncListener
  246. internalListener:internalListener];
  247. }
  248. /** Converts the public API options object to the internal options object. */
  249. - (FSTListenOptions *)internalOptionsForIncludeMetadataChanges:(BOOL)includeMetadataChanges {
  250. return [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:includeMetadataChanges
  251. includeDocumentMetadataChanges:includeMetadataChanges
  252. waitForSyncWhenOnline:NO];
  253. }
  254. @end
  255. #pragma mark - FIRDocumentReference (Internal)
  256. @implementation FIRDocumentReference (Internal)
  257. + (instancetype)referenceWithPath:(const ResourcePath &)path firestore:(FIRFirestore *)firestore {
  258. if (path.size() % 2 != 0) {
  259. FSTThrowInvalidArgument(
  260. @"Invalid document reference. Document references must have an even "
  261. "number of segments, but %s has %zu",
  262. path.CanonicalString().c_str(), path.size());
  263. }
  264. return [FIRDocumentReference referenceWithKey:DocumentKey{path} firestore:firestore];
  265. }
  266. + (instancetype)referenceWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  267. return [[FIRDocumentReference alloc] initWithKey:std::move(key) firestore:firestore];
  268. }
  269. - (const firebase::firestore::model::DocumentKey &)key {
  270. return _key;
  271. }
  272. @end
  273. NS_ASSUME_NONNULL_END