FIRDocumentReference.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 <GRPCClient/GRPCCall.h>
  20. #import "FIRFirestoreErrors.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/FIRSetOptions+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/resource_path.h"
  40. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  41. namespace util = firebase::firestore::util;
  42. using firebase::firestore::model::DocumentKey;
  43. using firebase::firestore::model::ResourcePath;
  44. NS_ASSUME_NONNULL_BEGIN
  45. #pragma mark - FIRDocumentListenOptions
  46. @interface FIRDocumentListenOptions ()
  47. - (instancetype)initWithIncludeMetadataChanges:(BOOL)includeMetadataChanges
  48. NS_DESIGNATED_INITIALIZER;
  49. @property(nonatomic, assign, readonly) BOOL includeMetadataChanges;
  50. @end
  51. @implementation FIRDocumentListenOptions
  52. + (instancetype)options {
  53. return [[FIRDocumentListenOptions alloc] init];
  54. }
  55. - (instancetype)initWithIncludeMetadataChanges:(BOOL)includeMetadataChanges {
  56. if (self = [super init]) {
  57. _includeMetadataChanges = includeMetadataChanges;
  58. }
  59. return self;
  60. }
  61. - (instancetype)init {
  62. return [self initWithIncludeMetadataChanges:NO];
  63. }
  64. - (instancetype)includeMetadataChanges:(BOOL)includeMetadataChanges {
  65. return [[FIRDocumentListenOptions alloc] initWithIncludeMetadataChanges:includeMetadataChanges];
  66. }
  67. @end
  68. #pragma mark - FIRDocumentReference
  69. @interface FIRDocumentReference ()
  70. - (instancetype)initWithKey:(DocumentKey)key
  71. firestore:(FIRFirestore *)firestore NS_DESIGNATED_INITIALIZER;
  72. @end
  73. @implementation FIRDocumentReference {
  74. DocumentKey _key;
  75. }
  76. - (instancetype)initWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  77. if (self = [super init]) {
  78. _key = std::move(key);
  79. _firestore = firestore;
  80. }
  81. return self;
  82. }
  83. #pragma mark - NSObject Methods
  84. - (BOOL)isEqual:(nullable id)other {
  85. if (other == self) return YES;
  86. if (![[other class] isEqual:[self class]]) return NO;
  87. return [self isEqualToReference:other];
  88. }
  89. - (BOOL)isEqualToReference:(nullable FIRDocumentReference *)reference {
  90. if (self == reference) return YES;
  91. if (reference == nil) return NO;
  92. return [self.firestore isEqual:reference.firestore] && self.key == reference.key;
  93. }
  94. - (NSUInteger)hash {
  95. NSUInteger hash = [self.firestore hash];
  96. hash = hash * 31u + self.key.Hash();
  97. return hash;
  98. }
  99. #pragma mark - Public Methods
  100. - (NSString *)documentID {
  101. return util::WrapNSString(self.key.path().last_segment());
  102. }
  103. - (FIRCollectionReference *)parent {
  104. return
  105. [FIRCollectionReference referenceWithPath:self.key.path().PopLast() firestore:self.firestore];
  106. }
  107. - (NSString *)path {
  108. return util::WrapNSString(self.key.path().CanonicalString());
  109. }
  110. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  111. if (!collectionPath) {
  112. FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  113. }
  114. const ResourcePath subPath = ResourcePath::FromString(util::MakeStringView(collectionPath));
  115. const ResourcePath path = self.key.path().Append(subPath);
  116. return [FIRCollectionReference referenceWithPath:path firestore:self.firestore];
  117. }
  118. - (void)setData:(NSDictionary<NSString *, id> *)documentData {
  119. return [self setData:documentData options:[FIRSetOptions overwrite] completion:nil];
  120. }
  121. - (void)setData:(NSDictionary<NSString *, id> *)documentData options:(FIRSetOptions *)options {
  122. return [self setData:documentData options:options completion:nil];
  123. }
  124. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  125. completion:(nullable void (^)(NSError *_Nullable error))completion {
  126. return [self setData:documentData options:[FIRSetOptions overwrite] completion:completion];
  127. }
  128. - (void)setData:(NSDictionary<NSString *, id> *)documentData
  129. options:(FIRSetOptions *)options
  130. completion:(nullable void (^)(NSError *_Nullable error))completion {
  131. FSTParsedSetData *parsed = options.isMerge
  132. ? [self.firestore.dataConverter parsedMergeData:documentData]
  133. : [self.firestore.dataConverter parsedSetData:documentData];
  134. return [self.firestore.client
  135. writeMutations:[parsed mutationsWithKey:self.key precondition:[FSTPrecondition none]]
  136. completion:completion];
  137. }
  138. - (void)updateData:(NSDictionary<id, id> *)fields {
  139. return [self updateData:fields completion:nil];
  140. }
  141. - (void)updateData:(NSDictionary<id, id> *)fields
  142. completion:(nullable void (^)(NSError *_Nullable error))completion {
  143. FSTParsedUpdateData *parsed = [self.firestore.dataConverter parsedUpdateData:fields];
  144. return [self.firestore.client
  145. writeMutations:[parsed mutationsWithKey:self.key
  146. precondition:[FSTPrecondition preconditionWithExists:YES]]
  147. completion:completion];
  148. }
  149. - (void)deleteDocument {
  150. return [self deleteDocumentWithCompletion:nil];
  151. }
  152. - (void)deleteDocumentWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  153. FSTDeleteMutation *mutation =
  154. [[FSTDeleteMutation alloc] initWithKey:self.key precondition:[FSTPrecondition none]];
  155. return [self.firestore.client writeMutations:@[ mutation ] completion:completion];
  156. }
  157. - (void)getDocumentWithCompletion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  158. NSError *_Nullable error))completion {
  159. FSTListenOptions *listenOptions =
  160. [[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. // TODO(dimond): Use proper error domain
  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 {
  192. completion(snapshot, nil);
  193. }
  194. };
  195. listenerRegistration =
  196. [self addSnapshotListenerInternalWithOptions:listenOptions listener:listener];
  197. dispatch_semaphore_signal(registered);
  198. }
  199. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRDocumentSnapshotBlock)listener {
  200. return [self addSnapshotListenerWithOptions:nil listener:listener];
  201. }
  202. - (id<FIRListenerRegistration>)addSnapshotListenerWithOptions:
  203. (nullable FIRDocumentListenOptions *)options
  204. listener:(FIRDocumentSnapshotBlock)listener {
  205. return [self addSnapshotListenerInternalWithOptions:[self internalOptions:options]
  206. listener:listener];
  207. }
  208. - (id<FIRListenerRegistration>)
  209. addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
  210. listener:(FIRDocumentSnapshotBlock)listener {
  211. FIRFirestore *firestore = self.firestore;
  212. FSTQuery *query = [FSTQuery queryWithPath:self.key.path()];
  213. const DocumentKey key = self.key;
  214. FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
  215. if (error) {
  216. listener(nil, error);
  217. return;
  218. }
  219. FSTAssert(snapshot.documents.count <= 1, @"Too many document returned on a document query");
  220. FSTDocument *document = [snapshot.documents documentForKey:key];
  221. FIRDocumentSnapshot *result = [FIRDocumentSnapshot snapshotWithFirestore:firestore
  222. documentKey:key
  223. document:document
  224. fromCache:snapshot.fromCache];
  225. listener(result, nil);
  226. };
  227. FSTAsyncQueryListener *asyncListener =
  228. [[FSTAsyncQueryListener alloc] initWithDispatchQueue:self.firestore.client.userDispatchQueue
  229. snapshotHandler:snapshotHandler];
  230. FSTQueryListener *internalListener =
  231. [firestore.client listenToQuery:query
  232. options:internalOptions
  233. viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  234. return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
  235. asyncListener:asyncListener
  236. internalListener:internalListener];
  237. }
  238. /** Converts the public API options object to the internal options object. */
  239. - (FSTListenOptions *)internalOptions:(nullable FIRDocumentListenOptions *)options {
  240. return
  241. [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:options.includeMetadataChanges
  242. includeDocumentMetadataChanges:options.includeMetadataChanges
  243. waitForSyncWhenOnline:NO];
  244. }
  245. @end
  246. #pragma mark - FIRDocumentReference (Internal)
  247. @implementation FIRDocumentReference (Internal)
  248. + (instancetype)referenceWithPath:(const ResourcePath &)path firestore:(FIRFirestore *)firestore {
  249. if (path.size() % 2 != 0) {
  250. FSTThrowInvalidArgument(
  251. @"Invalid document reference. Document references must have an even "
  252. "number of segments, but %s has %zu",
  253. path.CanonicalString().c_str(), path.size());
  254. }
  255. return [FIRDocumentReference referenceWithKey:DocumentKey{path} firestore:firestore];
  256. }
  257. + (instancetype)referenceWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  258. return [[FIRDocumentReference alloc] initWithKey:std::move(key) firestore:firestore];
  259. }
  260. - (const firebase::firestore::model::DocumentKey &)key {
  261. return _key;
  262. }
  263. @end
  264. NS_ASSUME_NONNULL_END