FIRDocumentReference.m 12 KB

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