FIRDocumentReference.mm 13 KB

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