FIRDocumentReference.mm 12 KB

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