FIRDocumentReference.m 11 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 "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. #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 =
  142. [self.firestore.dataConverter parsedSetData:documentData options:options];
  143. return [self.firestore.client
  144. writeMutations:[parsed mutationsWithKey:self.key precondition:[FSTPrecondition none]]
  145. completion:completion];
  146. }
  147. - (void)updateData:(NSDictionary<id, id> *)fields {
  148. return [self updateData:fields completion:nil];
  149. }
  150. - (void)updateData:(NSDictionary<id, id> *)fields
  151. completion:(nullable void (^)(NSError *_Nullable error))completion {
  152. FSTParsedUpdateData *parsed = [self.firestore.dataConverter parsedUpdateData:fields];
  153. return [self.firestore.client
  154. writeMutations:[parsed mutationsWithKey:self.key
  155. precondition:[FSTPrecondition preconditionWithExists:YES]]
  156. completion:completion];
  157. }
  158. - (void)deleteDocument {
  159. return [self deleteDocumentWithCompletion:nil];
  160. }
  161. - (void)deleteDocumentWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  162. FSTDeleteMutation *mutation =
  163. [[FSTDeleteMutation alloc] initWithKey:self.key precondition:[FSTPrecondition none]];
  164. return [self.firestore.client writeMutations:@[ mutation ] completion:completion];
  165. }
  166. - (void)getDocumentWithCompletion:(void (^)(FIRDocumentSnapshot *_Nullable document,
  167. NSError *_Nullable error))completion {
  168. FSTListenOptions *listenOptions =
  169. [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  170. includeDocumentMetadataChanges:YES
  171. waitForSyncWhenOnline:YES];
  172. dispatch_semaphore_t registered = dispatch_semaphore_create(0);
  173. __block id<FIRListenerRegistration> listenerRegistration;
  174. FIRDocumentSnapshotBlock listener = ^(FIRDocumentSnapshot *snapshot, NSError *error) {
  175. if (error) {
  176. completion(nil, error);
  177. return;
  178. }
  179. // Remove query first before passing event to user to avoid user actions affecting the
  180. // now stale query.
  181. dispatch_semaphore_wait(registered, DISPATCH_TIME_FOREVER);
  182. [listenerRegistration remove];
  183. if (!snapshot.exists && snapshot.metadata.fromCache) {
  184. // TODO(dimond): Reconsider how to raise missing documents when offline.
  185. // If we're online and the document doesn't exist then we call the completion with
  186. // a document with document.exists set to false. If we're offline however, we call the
  187. // completion handler with an error. Two options:
  188. // 1) Cache the negative response from the server so we can deliver that even when you're
  189. // offline.
  190. // 2) Actually call the completion handler with an error if the document doesn't exist when
  191. // you are offline.
  192. // TODO(dimond): Use proper error domain
  193. completion(nil,
  194. [NSError errorWithDomain:FIRFirestoreErrorDomain
  195. code:FIRFirestoreErrorCodeUnavailable
  196. userInfo:@{
  197. NSLocalizedDescriptionKey :
  198. @"Failed to get document because the client is offline.",
  199. }]);
  200. } else {
  201. completion(snapshot, nil);
  202. }
  203. };
  204. listenerRegistration =
  205. [self addSnapshotListenerInternalWithOptions:listenOptions listener:listener];
  206. dispatch_semaphore_signal(registered);
  207. }
  208. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRDocumentSnapshotBlock)listener {
  209. return [self addSnapshotListenerWithOptions:nil listener:listener];
  210. }
  211. - (id<FIRListenerRegistration>)addSnapshotListenerWithOptions:
  212. (nullable FIRDocumentListenOptions *)options
  213. listener:(FIRDocumentSnapshotBlock)listener {
  214. return [self addSnapshotListenerInternalWithOptions:[self internalOptions:options]
  215. listener:listener];
  216. }
  217. - (id<FIRListenerRegistration>)
  218. addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
  219. listener:(FIRDocumentSnapshotBlock)listener {
  220. FIRFirestore *firestore = self.firestore;
  221. FSTQuery *query = [FSTQuery queryWithPath:self.key.path];
  222. FSTDocumentKey *key = self.key;
  223. FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
  224. if (error) {
  225. listener(nil, error);
  226. return;
  227. }
  228. FSTAssert(snapshot.documents.count <= 1, @"Too many document returned on a document query");
  229. FSTDocument *document = [snapshot.documents documentForKey:key];
  230. FIRDocumentSnapshot *result = [FIRDocumentSnapshot snapshotWithFirestore:firestore
  231. documentKey:key
  232. document:document
  233. fromCache:snapshot.fromCache];
  234. listener(result, nil);
  235. };
  236. FSTAsyncQueryListener *asyncListener =
  237. [[FSTAsyncQueryListener alloc] initWithDispatchQueue:self.firestore.client.userDispatchQueue
  238. snapshotHandler:snapshotHandler];
  239. FSTQueryListener *internalListener =
  240. [firestore.client listenToQuery:query
  241. options:internalOptions
  242. viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  243. return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
  244. asyncListener:asyncListener
  245. internalListener:internalListener];
  246. }
  247. /** Converts the public API options object to the internal options object. */
  248. - (FSTListenOptions *)internalOptions:(nullable FIRDocumentListenOptions *)options {
  249. return
  250. [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:options.includeMetadataChanges
  251. includeDocumentMetadataChanges:options.includeMetadataChanges
  252. waitForSyncWhenOnline:NO];
  253. }
  254. @end
  255. NS_ASSUME_NONNULL_END