CollectionReference+WriteEncodable.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. import FirebaseFirestore
  18. public extension CollectionReference {
  19. /// Encodes an instance of `Encodable` and adds a new document to this collection
  20. /// with the encoded data, assigning it a document ID automatically.
  21. ///
  22. /// See `Firestore.Encoder` for more details about the encoding process.
  23. ///
  24. /// - Parameters:
  25. /// - value: An instance of `Encodable` to be encoded to a document.
  26. /// - encoder: An encoder instance to use to run the encoding.
  27. /// - completion: A block to execute once the document has been successfully
  28. /// written to the server. This block will not be called while
  29. /// the client is offline, though local changes will be visible
  30. /// immediately.
  31. /// - Returns: A `DocumentReference` pointing to the newly created document.
  32. func addDocument<T: Encodable>(from value: T,
  33. encoder: Firestore.Encoder = Firestore.Encoder(),
  34. completion: ((Error?) -> Void)? = nil) throws
  35. -> DocumentReference {
  36. return addDocument(data: try encoder.encode(value), completion: completion)
  37. }
  38. }