Skip to content

UserDataWriter #7842

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Firestore/Example/Tests/API/FSTAPIHelpers.mm
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
doc = Doc(path, version, parsed,
hasMutations ? DocumentState::kLocalMutations : DocumentState::kSynced);
}
return [[FIRDocumentSnapshot alloc] initWithFirestore:FSTTestFirestore().wrapped
return [[FIRDocumentSnapshot alloc] initWithFirestore:FSTTestFirestore()
documentKey:testutil::Key(path)
document:doc
fromCache:fromCache
Expand Down
6 changes: 4 additions & 2 deletions Firestore/Source/API/FIRDocumentSnapshot+Internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include "Firestore/core/src/api/api_fwd.h"
#include "Firestore/core/src/model/model_fwd.h"

@class FIRFirestore;

namespace api = firebase::firestore::api;
namespace model = firebase::firestore::model;

Expand All @@ -30,12 +32,12 @@ NS_ASSUME_NONNULL_BEGIN

- (instancetype)initWithSnapshot:(api::DocumentSnapshot &&)snapshot NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithFirestore:(std::shared_ptr<api::Firestore>)firestore
- (instancetype)initWithFirestore:(FIRFirestore *)firestore
documentKey:(model::DocumentKey)documentKey
document:(const absl::optional<model::Document> &)document
metadata:(api::SnapshotMetadata)metadata;

- (instancetype)initWithFirestore:(std::shared_ptr<api::Firestore>)firestore
- (instancetype)initWithFirestore:(FIRFirestore *)firestore
documentKey:(model::DocumentKey)documentKey
document:(const absl::optional<model::Document> &)document
fromCache:(bool)fromCache
Expand Down
115 changes: 28 additions & 87 deletions Firestore/Source/API/FIRDocumentSnapshot.mm
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
#import "Firestore/Source/API/FIRGeoPoint+Internal.h"
#import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
#import "Firestore/Source/API/FIRTimestamp+Internal.h"
#import "Firestore/Source/API/FSTUserDataWriter.h"
#import "Firestore/Source/API/converters.h"

#include "Firestore/Protos/nanopb/google/firestore/v1/document.nanopb.h"
#include "Firestore/core/src/api/document_reference.h"
#include "Firestore/core/src/api/document_snapshot.h"
#include "Firestore/core/src/api/firestore.h"
Expand All @@ -39,6 +41,7 @@
#include "Firestore/core/src/model/field_value.h"
#include "Firestore/core/src/model/field_value_options.h"
#include "Firestore/core/src/nanopb/nanopb_util.h"
#include "Firestore/core/src/remote/serializer.h"
#include "Firestore/core/src/util/exception.h"
#include "Firestore/core/src/util/hard_assert.h"
#include "Firestore/core/src/util/log.h"
Expand All @@ -60,9 +63,11 @@
using firebase::firestore::model::FieldValueOptions;
using firebase::firestore::model::ObjectValue;
using firebase::firestore::model::ServerTimestampBehavior;
using firebase::firestore::remote::Serializer;
using firebase::firestore::nanopb::MakeNSData;
using firebase::firestore::util::MakeString;
using firebase::firestore::util::ThrowInvalidArgument;
using firebase::firestore::google_firestore_v1_Value;

NS_ASSUME_NONNULL_BEGIN

Expand Down Expand Up @@ -90,32 +95,35 @@ ServerTimestampBehavior InternalServerTimestampBehavior(FIRServerTimestampBehavi
@implementation FIRDocumentSnapshot {
DocumentSnapshot _snapshot;

std::unique_ptr<Serializer> _serializer;
FIRSnapshotMetadata *_cachedMetadata;
}

- (instancetype)initWithSnapshot:(DocumentSnapshot &&)snapshot {
if (self = [super init]) {
_snapshot = std::move(snapshot);
_serializer.reset(new Serializer(_snapshot.firestore()->database_id()));
}
return self;
}

- (instancetype)initWithFirestore:(std::shared_ptr<Firestore>)firestore
- (instancetype)initWithFirestore:(FIRFirestore *)firestore
documentKey:(DocumentKey)documentKey
document:(const absl::optional<Document> &)document
metadata:(SnapshotMetadata)metadata {
DocumentSnapshot wrapped;
if (document.has_value()) {
wrapped =
DocumentSnapshot::FromDocument(std::move(firestore), document.value(), std::move(metadata));
DocumentSnapshot::FromDocument(firestore.wrapped, document.value(), std::move(metadata));
} else {
wrapped = DocumentSnapshot::FromNoDocument(std::move(firestore), std::move(documentKey),
wrapped = DocumentSnapshot::FromNoDocument(firestore.wrapped, std::move(documentKey),
std::move(metadata));
}
_serializer.reset(new Serializer(firestore.databaseID));
return [self initWithSnapshot:std::move(wrapped)];
}

- (instancetype)initWithFirestore:(std::shared_ptr<Firestore>)firestore
- (instancetype)initWithFirestore:(FIRFirestore *)firestore
documentKey:(DocumentKey)documentKey
document:(const absl::optional<Document> &)document
fromCache:(bool)fromCache
Expand Down Expand Up @@ -176,7 +184,7 @@ - (FIRSnapshotMetadata *)metadata {
absl::optional<ObjectValue> data = _snapshot.GetData();
if (!data) return nil;

return [self convertedObject:data->GetInternalValue() options:options];
return [self convertedValue:*data options:options];
}

- (nullable id)valueForField:(id)field {
Expand Down Expand Up @@ -208,94 +216,27 @@ - (FieldValueOptions)optionsForServerTimestampBehavior:
return FieldValueOptions(InternalServerTimestampBehavior(serverTimestampBehavior));
}

// TODO(mutabledocuments): Replace with UserDataWriter
// TODO(mutabledocuments): Replace this method and call UserDataWriter directly
- (id)convertedValue:(FieldValue)value options:(const FieldValueOptions &)options {
switch (value.type()) {
case FieldValue::Type::Null:
return [NSNull null];
case FieldValue::Type::Boolean:
return value.boolean_value() ? @YES : @NO;
case FieldValue::Type::Integer:
return @(value.integer_value());
case FieldValue::Type::Double:
return @(value.double_value());
case FieldValue::Type::Timestamp:
return [self convertedTimestamp:value];
case FieldValue::Type::ServerTimestamp:
return [self convertedServerTimestamp:value options:options];
case FieldValue::Type::String:
return util::MakeNSString(value.string_value());
case FieldValue::Type::Blob:
return MakeNSData(value.blob_value());
case FieldValue::Type::Reference:
return [self convertedReference:value];
case FieldValue::Type::GeoPoint:
return MakeFIRGeoPoint(value.geo_point_value());
case FieldValue::Type::Array:
return [self convertedArray:value.array_value() options:options];
case FieldValue::Type::Object:
return [self convertedObject:value.object_value() options:options];
}

UNREACHABLE();
}

- (id)convertedTimestamp:(const FieldValue &)value {
return MakeFIRTimestamp(value.timestamp_value());
}

- (id)convertedServerTimestamp:(const FieldValue &)value
options:(const FieldValueOptions &)options {
const auto &sts = value.server_timestamp_value();
FIRServerTimestampBehavior behavior;
switch (options.server_timestamp_behavior()) {
case ServerTimestampBehavior::kNone:
return [NSNull null];
case ServerTimestampBehavior::kEstimate: {
FieldValue local_write_time = FieldValue::FromTimestamp(sts.local_write_time());
return [self convertedTimestamp:local_write_time];
}
behavior = FIRServerTimestampBehaviorNone;
break;
case ServerTimestampBehavior::kEstimate:
behavior = FIRServerTimestampBehaviorEstimate;
break;
case ServerTimestampBehavior::kPrevious:
return sts.previous_value() ? [self convertedValue:*sts.previous_value() options:options]
: [NSNull null];
}

UNREACHABLE();
}

- (id)convertedReference:(const FieldValue &)value {
const auto &ref = value.reference_value();
const DatabaseId &refDatabase = ref.database_id();
const DatabaseId &database = _snapshot.firestore()->database_id();
if (refDatabase != database) {
LOG_WARN("Document %s contains a document reference within a different database (%s/%s) which "
"is not supported. It will be treated as a reference within the current database "
"(%s/%s) instead.",
_snapshot.CreateReference().Path(), refDatabase.project_id(),
refDatabase.database_id(), database.project_id(), database.database_id());
}
const DocumentKey &key = ref.key();
return [[FIRDocumentReference alloc] initWithKey:key firestore:_snapshot.firestore()];
}

- (NSArray<id> *)convertedArray:(const FieldValue::Array &)arrayContents
options:(const FieldValueOptions &)options {
NSMutableArray *result = [NSMutableArray arrayWithCapacity:arrayContents.size()];
for (const FieldValue &value : arrayContents) {
[result addObject:[self convertedValue:value options:options]];
behavior = FIRServerTimestampBehaviorPrevious;
break;
default:
HARD_FAIL("Unexpected server timestamp option: %s", options.server_timestamp_behavior());
}
return result;
}

- (NSDictionary<NSString *, id> *)convertedObject:(const FieldValue::Map &)objectValue
options:(const FieldValueOptions &)options {
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (const auto &kv : objectValue) {
const std::string &key = kv.first;
const FieldValue &value = kv.second;

result[util::MakeNSString(key)] = [self convertedValue:value options:options];
}
return result;
FSTUserDataWriter *dataWriter = [[FSTUserDataWriter alloc] initWithFirestore:_snapshot.firestore()
serverTimestampBehavior:behavior];
google_firestore_v1_Value protoValue = _serializer->EncodeFieldValue(value);
return [dataWriter convertedValue:protoValue];
}

@end
Expand Down
13 changes: 6 additions & 7 deletions Firestore/Source/API/FIRTransaction.mm
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,15 @@ - (void)getDocument:(FIRDocumentReference *)document
HARD_ASSERT(documents.size() == 1, "Mismatch in docs returned from document lookup.");
const MaybeDocument &internalDoc = documents.front();
if (internalDoc.is_no_document()) {
FIRDocumentSnapshot *doc =
[[FIRDocumentSnapshot alloc] initWithFirestore:self.firestore.wrapped
documentKey:document.key
document:absl::nullopt
fromCache:false
hasPendingWrites:false];
FIRDocumentSnapshot *doc = [[FIRDocumentSnapshot alloc] initWithFirestore:self.firestore
documentKey:document.key
document:absl::nullopt
fromCache:false
hasPendingWrites:false];
completion(doc, nil);
} else if (internalDoc.is_document()) {
FIRDocumentSnapshot *doc =
[[FIRDocumentSnapshot alloc] initWithFirestore:self.firestore.wrapped
[[FIRDocumentSnapshot alloc] initWithFirestore:self.firestore
documentKey:internalDoc.key()
document:Document(internalDoc)
fromCache:false
Expand Down
2 changes: 1 addition & 1 deletion Firestore/Source/API/FSTUserDataReader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ - (google_firestore_v1_Value)parseDictionary:(NSDictionary<NSString *, id> *)dic
// Compute the final size of the fields array, which contains an entry for
// all fields that are not FieldValue sentinels
__block pb_size_t count = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *) {
[dict enumerateKeysAndObjectsUsingBlock:^(NSString *, id value, BOOL *) {
if (![value isKindOfClass:[FIRFieldValue class]]) {
++count;
}
Expand Down
40 changes: 40 additions & 0 deletions Firestore/Source/API/FSTUserDataWriter.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 2021 Google LLC
*
* 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 <Foundation/Foundation.h>

#include <memory>

#include "Firestore/Protos/nanopb/google/firestore/v1/document.nanopb.h"
#include "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
#include "Firestore/core/src/api/api_fwd.h"

namespace api = firebase::firestore::api;

/**
* Converts Firestore's internal types to the API types that we expose to the
* user.
*/
@interface FSTUserDataWriter : NSObject

- (instancetype)init NS_UNAVAILABLE;

- (instancetype)initWithFirestore:(std::shared_ptr<api::Firestore>)firestore
serverTimestampBehavior:(FIRServerTimestampBehavior)serverTimestampBehavior;

- (id)convertedValue:(const firebase::firestore::google_firestore_v1_Value&)value;

@end
Loading