Files
firebase-ios-sdk/FirebaseDatabase/Swift/Sources/Codable/DatabaseReference+WriteEncodable.swift
T

48 lines
1.9 KiB
Swift
Raw Normal View History

2021-03-13 16:42:14 +01:00
/*
* Copyright 2020 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
#if SWIFT_PACKAGE
@_exported import FirebaseDatabaseInternal
#endif // SWIFT_PACKAGE
import FirebaseSharedSwift
2021-03-13 16:42:14 +01:00
2022-01-21 13:03:15 -08:00
public extension DatabaseReference {
2021-03-13 16:42:14 +01:00
/// Encodes an instance of `Encodable` and overwrites the encoded data
/// to the path referred by this `DatabaseReference`. If no value exists,
/// it is created. If a value already exists, it is overwritten.
///
/// See `Database.Encoder` for more details about the encoding process.
///
/// - 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 value 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.
2022-01-21 13:03:15 -08:00
func setValue<T: Encodable>(from value: T,
encoder: Database.Encoder = Database.Encoder(),
completion: ((Error?) -> Void)? =
nil) throws {
2021-03-13 16:42:14 +01:00
let encoded = try encoder.encode(value)
if let completion = completion {
setValue(encoded, withCompletionBlock: { error, _ in completion(error) })
} else {
setValue(encoded)
}
}
}