CollectionReference+WriteEncodable.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Copyright 2019 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. #if SWIFT_PACKAGE
  18. @_exported import FirebaseFirestoreInternalWrapper
  19. #else
  20. @_exported import FirebaseFirestoreInternal
  21. #endif // SWIFT_PACKAGE
  22. public extension CollectionReference {
  23. /// Encodes an instance of `Encodable` and adds a new document to this collection
  24. /// with the encoded data, assigning it a document ID automatically.
  25. ///
  26. /// See `Firestore.Encoder` for more details about the encoding process.
  27. ///
  28. /// - Parameters:
  29. /// - value: An instance of `Encodable` to be encoded to a document.
  30. /// - encoder: An encoder instance to use to run the encoding.
  31. /// - completion: A block to execute once the document has been successfully
  32. /// written to the server. This block will not be called while
  33. /// the client is offline, though local changes will be visible
  34. /// immediately.
  35. /// - Returns: A `DocumentReference` pointing to the newly created document.
  36. @discardableResult
  37. func addDocument<T: Encodable>(from value: T,
  38. encoder: Firestore.Encoder = Firestore.Encoder(),
  39. completion: ((Error?) -> Void)? = nil) throws
  40. -> DocumentReference {
  41. let encoded = try encoder.encode(value)
  42. return addDocument(data: encoded, completion: completion)
  43. }
  44. }