aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Source/API/FIRDocumentReference.mm
blob: 5ad606c9635ec6822ab69e0456869bd91263fa81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright 2017 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "FIRDocumentReference.h"

#import <GRPCClient/GRPCCall.h>

#include <memory>
#include <utility>

#import "FIRFirestoreErrors.h"
#import "FIRFirestoreSource.h"
#import "FIRSnapshotMetadata.h"
#import "Firestore/Source/API/FIRCollectionReference+Internal.h"
#import "Firestore/Source/API/FIRDocumentReference+Internal.h"
#import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
#import "Firestore/Source/API/FIRFirestore+Internal.h"
#import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
#import "Firestore/Source/API/FSTUserDataConverter.h"
#import "Firestore/Source/Core/FSTEventManager.h"
#import "Firestore/Source/Core/FSTFirestoreClient.h"
#import "Firestore/Source/Core/FSTQuery.h"
#import "Firestore/Source/Model/FSTDocumentSet.h"
#import "Firestore/Source/Model/FSTFieldValue.h"
#import "Firestore/Source/Model/FSTMutation.h"
#import "Firestore/Source/Util/FSTAssert.h"
#import "Firestore/Source/Util/FSTAsyncQueryListener.h"
#import "Firestore/Source/Util/FSTUsageValidation.h"

#include "Firestore/core/src/firebase/firestore/model/document_key.h"
#include "Firestore/core/src/firebase/firestore/model/precondition.h"
#include "Firestore/core/src/firebase/firestore/model/resource_path.h"
#include "Firestore/core/src/firebase/firestore/util/string_apple.h"

namespace util = firebase::firestore::util;
using firebase::firestore::model::DocumentKey;
using firebase::firestore::model::Precondition;
using firebase::firestore::model::ResourcePath;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - FIRDocumentReference

@interface FIRDocumentReference ()
- (instancetype)initWithKey:(DocumentKey)key
                  firestore:(FIRFirestore *)firestore NS_DESIGNATED_INITIALIZER;
@end

@implementation FIRDocumentReference {
  DocumentKey _key;
}

- (instancetype)initWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  if (self = [super init]) {
    _key = std::move(key);
    _firestore = firestore;
  }
  return self;
}

#pragma mark - NSObject Methods

- (BOOL)isEqual:(nullable id)other {
  if (other == self) return YES;
  if (![[other class] isEqual:[self class]]) return NO;

  return [self isEqualToReference:other];
}

- (BOOL)isEqualToReference:(nullable FIRDocumentReference *)reference {
  if (self == reference) return YES;
  if (reference == nil) return NO;
  return [self.firestore isEqual:reference.firestore] && self.key == reference.key;
}

- (NSUInteger)hash {
  NSUInteger hash = [self.firestore hash];
  hash = hash * 31u + self.key.Hash();
  return hash;
}

#pragma mark - Public Methods

- (NSString *)documentID {
  return util::WrapNSString(self.key.path().last_segment());
}

- (FIRCollectionReference *)parent {
  return
      [FIRCollectionReference referenceWithPath:self.key.path().PopLast() firestore:self.firestore];
}

- (NSString *)path {
  return util::WrapNSString(self.key.path().CanonicalString());
}

- (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  if (!collectionPath) {
    FSTThrowInvalidArgument(@"Collection path cannot be nil.");
  }
  const ResourcePath subPath = ResourcePath::FromString(util::MakeStringView(collectionPath));
  const ResourcePath path = self.key.path().Append(subPath);
  return [FIRCollectionReference referenceWithPath:path firestore:self.firestore];
}

- (void)setData:(NSDictionary<NSString *, id> *)documentData {
  return [self setData:documentData merge:NO completion:nil];
}

- (void)setData:(NSDictionary<NSString *, id> *)documentData merge:(BOOL)merge {
  return [self setData:documentData merge:merge completion:nil];
}

- (void)setData:(NSDictionary<NSString *, id> *)documentData
    mergeFields:(NSArray<id> *)mergeFields {
  return [self setData:documentData mergeFields:mergeFields completion:nil];
}

- (void)setData:(NSDictionary<NSString *, id> *)documentData
     completion:(nullable void (^)(NSError *_Nullable error))completion {
  return [self setData:documentData merge:NO completion:completion];
}

- (void)setData:(NSDictionary<NSString *, id> *)documentData
          merge:(BOOL)merge
     completion:(nullable void (^)(NSError *_Nullable error))completion {
  FSTParsedSetData *parsed =
      merge ? [self.firestore.dataConverter parsedMergeData:documentData fieldMask:nil]
            : [self.firestore.dataConverter parsedSetData:documentData];
  return [self.firestore.client
      writeMutations:[parsed mutationsWithKey:self.key precondition:Precondition::None()]
          completion:completion];
}

- (void)setData:(NSDictionary<NSString *, id> *)documentData
    mergeFields:(NSArray<id> *)mergeFields
     completion:(nullable void (^)(NSError *_Nullable error))completion {
  FSTParsedSetData *parsed =
      [self.firestore.dataConverter parsedMergeData:documentData fieldMask:mergeFields];
  return [self.firestore.client
      writeMutations:[parsed mutationsWithKey:self.key precondition:Precondition::None()]
          completion:completion];
}

- (void)updateData:(NSDictionary<id, id> *)fields {
  return [self updateData:fields completion:nil];
}

- (void)updateData:(NSDictionary<id, id> *)fields
        completion:(nullable void (^)(NSError *_Nullable error))completion {
  FSTParsedUpdateData *parsed = [self.firestore.dataConverter parsedUpdateData:fields];
  return [self.firestore.client
      writeMutations:[parsed mutationsWithKey:self.key precondition:Precondition::Exists(true)]
          completion:completion];
}

- (void)deleteDocument {
  return [self deleteDocumentWithCompletion:nil];
}

- (void)deleteDocumentWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  FSTDeleteMutation *mutation =
      [[FSTDeleteMutation alloc] initWithKey:self.key precondition:Precondition::None()];
  return [self.firestore.client writeMutations:@[ mutation ] completion:completion];
}

- (void)getDocumentWithCompletion:(void (^)(FIRDocumentSnapshot *_Nullable document,
                                            NSError *_Nullable error))completion {
  return [self getDocumentWithSource:FIRFirestoreSourceDefault completion:completion];
}

- (void)getDocumentWithSource:(FIRFirestoreSource)source
                   completion:(void (^)(FIRDocumentSnapshot *_Nullable document,
                                        NSError *_Nullable error))completion {
  if (source == FIRFirestoreSourceCache) {
    [self.firestore.client getDocumentFromLocalCache:self completion:completion];
    return;
  }

  FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
                                                             includeDocumentMetadataChanges:YES
                                                                      waitForSyncWhenOnline:YES];

  dispatch_semaphore_t registered = dispatch_semaphore_create(0);
  __block id<FIRListenerRegistration> listenerRegistration;
  FIRDocumentSnapshotBlock listener = ^(FIRDocumentSnapshot *snapshot, NSError *error) {
    if (error) {
      completion(nil, error);
      return;
    }

    // Remove query first before passing event to user to avoid user actions affecting the
    // now stale query.
    dispatch_semaphore_wait(registered, DISPATCH_TIME_FOREVER);
    [listenerRegistration remove];

    if (!snapshot.exists && snapshot.metadata.fromCache) {
      // TODO(dimond): Reconsider how to raise missing documents when offline.
      // If we're online and the document doesn't exist then we call the completion with
      // a document with document.exists set to false. If we're offline however, we call the
      // completion handler with an error. Two options:
      // 1) Cache the negative response from the server so we can deliver that even when you're
      //    offline.
      // 2) Actually call the completion handler with an error if the document doesn't exist when
      //    you are offline.
      completion(nil,
                 [NSError errorWithDomain:FIRFirestoreErrorDomain
                                     code:FIRFirestoreErrorCodeUnavailable
                                 userInfo:@{
                                   NSLocalizedDescriptionKey :
                                       @"Failed to get document because the client is offline.",
                                 }]);
    } else if (snapshot.exists && snapshot.metadata.fromCache &&
               source == FIRFirestoreSourceServer) {
      completion(nil,
                 [NSError errorWithDomain:FIRFirestoreErrorDomain
                                     code:FIRFirestoreErrorCodeUnavailable
                                 userInfo:@{
                                   NSLocalizedDescriptionKey :
                                       @"Failed to get document from server. (However, this "
                                       @"document does exist in the local cache. Run again "
                                       @"without setting source to FIRFirestoreSourceServer to "
                                       @"retrieve the cached document.)"
                                 }]);
    } else {
      completion(snapshot, nil);
    }
  };

  listenerRegistration = [self addSnapshotListenerInternalWithOptions:options listener:listener];
  dispatch_semaphore_signal(registered);
}

- (id<FIRListenerRegistration>)addSnapshotListener:(FIRDocumentSnapshotBlock)listener {
  return [self addSnapshotListenerWithIncludeMetadataChanges:NO listener:listener];
}

- (id<FIRListenerRegistration>)
addSnapshotListenerWithIncludeMetadataChanges:(BOOL)includeMetadataChanges
                                     listener:(FIRDocumentSnapshotBlock)listener {
  FSTListenOptions *options =
      [self internalOptionsForIncludeMetadataChanges:includeMetadataChanges];
  return [self addSnapshotListenerInternalWithOptions:options listener:listener];
}

- (id<FIRListenerRegistration>)
addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
                              listener:(FIRDocumentSnapshotBlock)listener {
  FIRFirestore *firestore = self.firestore;
  FSTQuery *query = [FSTQuery queryWithPath:self.key.path()];
  const DocumentKey key = self.key;

  FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
    if (error) {
      listener(nil, error);
      return;
    }

    FSTAssert(snapshot.documents.count <= 1, @"Too many document returned on a document query");
    FSTDocument *document = [snapshot.documents documentForKey:key];

    FIRDocumentSnapshot *result = [FIRDocumentSnapshot snapshotWithFirestore:firestore
                                                                 documentKey:key
                                                                    document:document
                                                                   fromCache:snapshot.fromCache];
    listener(result, nil);
  };

  FSTAsyncQueryListener *asyncListener =
      [[FSTAsyncQueryListener alloc] initWithExecutor:self.firestore.client.userExecutor
                                      snapshotHandler:snapshotHandler];

  FSTQueryListener *internalListener =
      [firestore.client listenToQuery:query
                              options:internalOptions
                  viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
                                           asyncListener:asyncListener
                                        internalListener:internalListener];
}

/** Converts the public API options object to the internal options object. */
- (FSTListenOptions *)internalOptionsForIncludeMetadataChanges:(BOOL)includeMetadataChanges {
  return [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:includeMetadataChanges
                                        includeDocumentMetadataChanges:includeMetadataChanges
                                                 waitForSyncWhenOnline:NO];
}

@end

#pragma mark - FIRDocumentReference (Internal)

@implementation FIRDocumentReference (Internal)

+ (instancetype)referenceWithPath:(const ResourcePath &)path firestore:(FIRFirestore *)firestore {
  if (path.size() % 2 != 0) {
    FSTThrowInvalidArgument(
        @"Invalid document reference. Document references must have an even "
         "number of segments, but %s has %zu",
        path.CanonicalString().c_str(), path.size());
  }
  return [FIRDocumentReference referenceWithKey:DocumentKey{path} firestore:firestore];
}

+ (instancetype)referenceWithKey:(DocumentKey)key firestore:(FIRFirestore *)firestore {
  return [[FIRDocumentReference alloc] initWithKey:std::move(key) firestore:firestore];
}

- (const firebase::firestore::model::DocumentKey &)key {
  return _key;
}

@end

NS_ASSUME_NONNULL_END