aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Source/API/FIRDocumentSnapshot.mm
blob: ddf4cca367fe760ed9967d32a0313aa8eb3bcee3 (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
/*
 * 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 "FIRDocumentSnapshot.h"

#import "Firestore/Source/API/FIRDocumentReference+Internal.h"
#import "Firestore/Source/API/FIRFieldPath+Internal.h"
#import "Firestore/Source/API/FIRFirestore+Internal.h"
#import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
#import "Firestore/Source/API/FIRSnapshotOptions+Internal.h"
#import "Firestore/Source/Model/FSTDocument.h"
#import "Firestore/Source/Model/FSTDocumentKey.h"
#import "Firestore/Source/Model/FSTFieldValue.h"
#import "Firestore/Source/Model/FSTPath.h"
#import "Firestore/Source/Util/FSTAssert.h"
#import "Firestore/Source/Util/FSTUsageValidation.h"

#include "Firestore/core/src/firebase/firestore/model/database_id.h"
#include "Firestore/core/src/firebase/firestore/util/string_apple.h"

namespace util = firebase::firestore::util;
using firebase::firestore::model::DatabaseId;

NS_ASSUME_NONNULL_BEGIN

@interface FIRDocumentSnapshot ()

- (instancetype)initWithFirestore:(FIRFirestore *)firestore
                      documentKey:(FSTDocumentKey *)documentKey
                         document:(nullable FSTDocument *)document
                        fromCache:(BOOL)fromCache NS_DESIGNATED_INITIALIZER;

@property(nonatomic, strong, readonly) FIRFirestore *firestore;
@property(nonatomic, strong, readonly) FSTDocumentKey *internalKey;
@property(nonatomic, strong, readonly, nullable) FSTDocument *internalDocument;
@property(nonatomic, assign, readonly) BOOL fromCache;

@end

@implementation FIRDocumentSnapshot (Internal)

+ (instancetype)snapshotWithFirestore:(FIRFirestore *)firestore
                          documentKey:(FSTDocumentKey *)documentKey
                             document:(nullable FSTDocument *)document
                            fromCache:(BOOL)fromCache {
  return [[[self class] alloc] initWithFirestore:firestore
                                     documentKey:documentKey
                                        document:document
                                       fromCache:fromCache];
}

@end

@implementation FIRDocumentSnapshot {
  FIRSnapshotMetadata *_cachedMetadata;
}

@dynamic metadata;

- (instancetype)initWithFirestore:(FIRFirestore *)firestore
                      documentKey:(FSTDocumentKey *)documentKey
                         document:(nullable FSTDocument *)document
                        fromCache:(BOOL)fromCache {
  if (self = [super init]) {
    _firestore = firestore;
    _internalKey = documentKey;
    _internalDocument = document;
    _fromCache = fromCache;
  }
  return self;
}

// NSObject Methods
- (BOOL)isEqual:(nullable id)other {
  if (other == self) return YES;
  // self class could be FIRDocumentSnapshot or subtype. So we compare with base type explicitly.
  if (![other isKindOfClass:[FIRDocumentSnapshot class]]) return NO;

  return [self isEqualToSnapshot:other];
}

- (BOOL)isEqualToSnapshot:(nullable FIRDocumentSnapshot *)snapshot {
  if (self == snapshot) return YES;
  if (snapshot == nil) return NO;

  return [self.firestore isEqual:snapshot.firestore] &&
         [self.internalKey isEqual:snapshot.internalKey] &&
         (self.internalDocument == snapshot.internalDocument ||
          [self.internalDocument isEqual:snapshot.internalDocument]) &&
         self.fromCache == snapshot.fromCache;
}

- (NSUInteger)hash {
  NSUInteger hash = [self.firestore hash];
  hash = hash * 31u + [self.internalKey hash];
  hash = hash * 31u + [self.internalDocument hash];
  hash = hash * 31u + (self.fromCache ? 1 : 0);
  return hash;
}

@dynamic exists;

- (BOOL)exists {
  return _internalDocument != nil;
}

- (FIRDocumentReference *)reference {
  return [FIRDocumentReference referenceWithKey:self.internalKey firestore:self.firestore];
}

- (NSString *)documentID {
  return [self.internalKey.path lastSegment];
}

- (FIRSnapshotMetadata *)metadata {
  if (!_cachedMetadata) {
    _cachedMetadata = [FIRSnapshotMetadata
        snapshotMetadataWithPendingWrites:self.internalDocument.hasLocalMutations
                                fromCache:self.fromCache];
  }
  return _cachedMetadata;
}

- (nullable NSDictionary<NSString *, id> *)data {
  return [self dataWithOptions:[FIRSnapshotOptions defaultOptions]];
}

- (nullable NSDictionary<NSString *, id> *)dataWithOptions:(FIRSnapshotOptions *)options {
  return self.internalDocument == nil
             ? nil
             : [self convertedObject:[self.internalDocument data]
                             options:[FSTFieldValueOptions optionsForSnapshotOptions:options]];
}

- (nullable id)valueForField:(id)field {
  return [self valueForField:field options:[FIRSnapshotOptions defaultOptions]];
}

- (nullable id)valueForField:(id)field options:(FIRSnapshotOptions *)options {
  FIRFieldPath *fieldPath;

  if ([field isKindOfClass:[NSString class]]) {
    fieldPath = [FIRFieldPath pathWithDotSeparatedString:field];
  } else if ([field isKindOfClass:[FIRFieldPath class]]) {
    fieldPath = field;
  } else {
    FSTThrowInvalidArgument(@"Subscript key must be an NSString or FIRFieldPath.");
  }

  FSTFieldValue *fieldValue = [[self.internalDocument data] valueForPath:fieldPath.internalValue];
  return fieldValue == nil
             ? nil
             : [self convertedValue:fieldValue
                            options:[FSTFieldValueOptions optionsForSnapshotOptions:options]];
}

- (nullable id)objectForKeyedSubscript:(id)key {
  return [self valueForField:key];
}

- (id)convertedValue:(FSTFieldValue *)value options:(FSTFieldValueOptions *)options {
  if ([value isKindOfClass:[FSTObjectValue class]]) {
    return [self convertedObject:(FSTObjectValue *)value options:options];
  } else if ([value isKindOfClass:[FSTArrayValue class]]) {
    return [self convertedArray:(FSTArrayValue *)value options:options];
  } else if ([value isKindOfClass:[FSTReferenceValue class]]) {
    FSTReferenceValue *ref = (FSTReferenceValue *)value;
    const DatabaseId *refDatabase = ref.databaseID;
    const DatabaseId *database = self.firestore.databaseID;
    if (*refDatabase != *database) {
      // TODO(b/32073923): Log this as a proper warning.
      NSLog(
          @"WARNING: Document %@ contains a document reference within a different database "
           "(%@/%@) which is not supported. It will be treated as a reference within the "
           "current database (%@/%@) instead.",
          self.reference.path, util::WrapNSStringNoCopy(refDatabase->project_id()),
          util::WrapNSStringNoCopy(refDatabase->database_id()),
          util::WrapNSStringNoCopy(database->project_id()),
          util::WrapNSStringNoCopy(database->database_id()));
    }
    return [FIRDocumentReference referenceWithKey:[ref valueWithOptions:options]
                                        firestore:self.firestore];
  } else {
    return [value valueWithOptions:options];
  }
}

- (NSDictionary<NSString *, id> *)convertedObject:(FSTObjectValue *)objectValue
                                          options:(FSTFieldValueOptions *)options {
  NSMutableDictionary *result = [NSMutableDictionary dictionary];
  [objectValue.internalValue
      enumerateKeysAndObjectsUsingBlock:^(NSString *key, FSTFieldValue *value, BOOL *stop) {
        result[key] = [self convertedValue:value options:options];
      }];
  return result;
}

- (NSArray<id> *)convertedArray:(FSTArrayValue *)arrayValue
                        options:(FSTFieldValueOptions *)options {
  NSArray<FSTFieldValue *> *internalValue = arrayValue.internalValue;
  NSMutableArray *result = [NSMutableArray arrayWithCapacity:internalValue.count];
  [internalValue enumerateObjectsUsingBlock:^(id value, NSUInteger idx, BOOL *stop) {
    [result addObject:[self convertedValue:value options:options]];
  }];
  return result;
}

@end

@interface FIRQueryDocumentSnapshot ()

- (instancetype)initWithFirestore:(FIRFirestore *)firestore
                      documentKey:(FSTDocumentKey *)documentKey
                         document:(FSTDocument *)document
                        fromCache:(BOOL)fromCache NS_DESIGNATED_INITIALIZER;

@end

@implementation FIRQueryDocumentSnapshot

- (instancetype)initWithFirestore:(FIRFirestore *)firestore
                      documentKey:(FSTDocumentKey *)documentKey
                         document:(FSTDocument *)document
                        fromCache:(BOOL)fromCache {
  self = [super initWithFirestore:firestore
                      documentKey:documentKey
                         document:document
                        fromCache:fromCache];
  return self;
}

- (NSDictionary<NSString *, id> *)data {
  NSDictionary<NSString *, id> *data = [super data];
  FSTAssert(data, @"Document in a QueryDocumentSnapshot should exist");
  return data;
}

- (NSDictionary<NSString *, id> *)dataWithOptions:(FIRSnapshotOptions *)options {
  NSDictionary<NSString *, id> *data = [super dataWithOptions:options];
  FSTAssert(data, @"Document in a QueryDocumentSnapshot should exist");
  return data;
}

@end

NS_ASSUME_NONNULL_END