FIRDocumentReference.m 11 KB

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