FIRDocumentReference.mm 12 KB

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