Skip to content
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

Require explicit typing for DocumentSnapshot decoding. DocumentReference decoding. #9101

Merged
1 change: 1 addition & 0 deletions Firestore/Swift/Source/Codable/CodableErrors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
public enum FirestoreDecodingError: Error {
case decodingIsNotSupported(String)
case fieldNameConflict(String)
case `internal`
}

public enum FirestoreEncodingError: Error {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* 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
import FirebaseFirestore

public extension DocumentReference {
/// Fetches and decodes the document referenced by this `DocumentReference`.
///
/// This allows users to retrieve a Firestore document and have it decoded to an instance of
/// caller-specified type.
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
/// ```swift
/// ref.getDocument(as: Book.self) { result in
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
/// do {
/// let book = try result.get()
/// } catch {
/// // Handle error
/// }
/// }
/// ```
/// - Parameters:
/// - as: A `Decodable` type to convert the document fields to.
/// - serverTimestampBehavior: Configures how server timestamps that have
/// not yet been set to their final value are returned from the snapshot.
/// - decoder: The decoder to use to convert the document. Defaults to use
/// default decoder.
/// - completion: The closure to call when the document snapshot has been fetched and decoded.
func getDocument<T: Decodable>(as type: T.Type,
schmidt-sebastian marked this conversation as resolved.
Show resolved Hide resolved
with serverTimestampBehavior: ServerTimestampBehavior =
.none,
decoder: Firestore.Decoder = .init(),
completion: @escaping (Result<T, Error>) -> Void) {
getDocument { snapshot, error in
guard let snapshot = snapshot else {
completion(.failure(error ?? FirestoreDecodingError.internal))
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
return
}
let result = Result {
try snapshot.data(as: T.self,
with: serverTimestampBehavior,
decoder: decoder)
}
completion(result)
}
}

#if compiler(>=5.5) && canImport(_Concurrency)
/// Fetches and decodes the document referenced by this `DocumentReference`.
///
/// This allows users to retrieve a Firestore document and have it decoded to an instance of
/// caller-specified type.
/// ```swift
/// do {
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
/// let book = try await ref.getDocument(as: Book.self)
/// } catch {
/// // Handle error
/// }
/// ```
/// - Parameters:
/// - as: A `Decodable` type to convert the document fields to.
/// - serverTimestampBehavior: Configures how server timestamps that have
/// not yet been set to their final value are returned from the snapshot.
/// - decoder: The decoder to use to convert the document. Defaults to use
/// default decoder.
/// - Returns: This instance of the supplied `Decodable` type `T`.
@available(iOS 15, tvOS 15, macOS 12, watchOS 8, *)
func getDocument<T: Decodable>(as type: T.Type,
with serverTimestampBehavior: ServerTimestampBehavior =
.none,
decoder: Firestore.Decoder = .init()) async throws -> T {
let snapshot = try await getDocument()
return try snapshot.data(as: T.self,
with: serverTimestampBehavior,
decoder: decoder)
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public extension DocumentReference {
/// - Parameters:
/// - value: An instance of `Encodable` to be encoded to a document.
/// - encoder: An encoder instance to use to run the encoding.
/// - completion: A block to execute once the document has been successfully
/// - completion: A closure to execute once the document has been successfully
/// written to the server. This block will not be called while
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
/// the client is offline, though local changes will be visible
/// immediately.
Expand All @@ -49,7 +49,7 @@ public extension DocumentReference {
/// - merge: Whether to merge the provided `Encodable` into any existing
/// document.
/// - encoder: An encoder instance to use to run the encoding.
/// - completion: A block to execute once the document has been successfully
/// - completion: A closure to execute once the document has been successfully
/// written to the server. This block will not be called while
/// the client is offline, though local changes will be visible
/// immediately.
Expand All @@ -76,7 +76,7 @@ public extension DocumentReference {
/// merge. Fields can contain dots to reference nested fields within the
/// document.
/// - encoder: An encoder instance to use to run the encoding.
/// - completion: A block to execute once the document has been successfully
/// - completion: A closure to execute once the document has been successfully
/// written to the server. This block will not be called while
/// the client is offline, though local changes will be visible
/// immediately.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import FirebaseFirestore

public extension DocumentSnapshot {
/// Retrieves all fields in a document and converts them to an instance of
/// caller-specified type. Returns `nil` if the document does not exist.
/// caller-specified type.
///
/// By default, server-provided timestamps that have not yet been set to their
/// final value will be returned as `NSNull`. Pass `serverTimestampBehavior`
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -31,15 +31,12 @@ public extension DocumentSnapshot {
/// - type: The type to convert the document fields to.
/// - serverTimestampBehavior: Configures how server timestamps that have
/// not yet been set to their final value are returned from the snapshot.
/// - decoder: The decoder to use to convert the document. `nil` to use
/// - decoder: The decoder to use to convert the document. Defaults to use
/// default decoder.
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
func data<T: Decodable>(as type: T.Type,
with serverTimestampBehavior: ServerTimestampBehavior = .none,
decoder: Firestore.Decoder? = nil) throws -> T? {
let d = decoder ?? Firestore.Decoder()
if let data = data(with: serverTimestampBehavior) {
return try d.decode(T.self, from: data, in: reference)
}
return nil
decoder: Firestore.Decoder = .init()) throws -> T {
let data: Any = data(with: serverTimestampBehavior) ?? NSNull()
mortenbekditlevsen marked this conversation as resolved.
Show resolved Hide resolved
return try decoder.decode(T.self, from: data, in: reference)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public extension Firestore {
/// decoded.
/// - Returns: An instance of specified type by the first parameter.
public func decode<T: Decodable>(_: T.Type,
from container: [String: Any],
from container: Any,
in document: DocumentReference? = nil) throws -> T {
let decoder = _FirestoreDecoder(referencing: container)
if let doc = document {
Expand Down