BSONObjectId+Codable.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2025 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. #if SWIFT_PACKAGE
  17. @_exported import FirebaseFirestoreInternalWrapper
  18. #else
  19. @_exported import FirebaseFirestoreInternal
  20. #endif // SWIFT_PACKAGE
  21. /**
  22. * A protocol describing the encodable properties of an BSONObjectId.
  23. *
  24. * Note: this protocol exists as a workaround for the Swift compiler: if the BSONObjectId class
  25. * was extended directly to conform to Codable, the methods implementing the protocol would be need
  26. * to be marked required but that can't be done in an extension. Declaring the extension on the
  27. * protocol sidesteps this issue.
  28. */
  29. private protocol CodableBSONObjectId: Codable {
  30. var value: String { get }
  31. init(_ value: String)
  32. }
  33. /** The keys in an BSONObjectId. Must match the properties of CodableBSONObjectId. */
  34. private enum BSONObjectIdKeys: String, CodingKey {
  35. case value
  36. }
  37. /**
  38. * An extension of BSONObjectId that implements the behavior of the Codable protocol.
  39. *
  40. * Note: this is implemented manually here because the Swift compiler can't synthesize these methods
  41. * when declaring an extension to conform to Codable.
  42. */
  43. extension CodableBSONObjectId {
  44. public init(from decoder: Decoder) throws {
  45. let container = try decoder.container(keyedBy: BSONObjectIdKeys.self)
  46. let value = try container.decode(String.self, forKey: .value)
  47. self.init(value)
  48. }
  49. public func encode(to encoder: Encoder) throws {
  50. var container = encoder.container(keyedBy: BSONObjectIdKeys.self)
  51. try container.encode(value, forKey: .value)
  52. }
  53. }
  54. /** Extends BSONObjectId to conform to Codable. */
  55. extension FirebaseFirestore.BSONObjectId: FirebaseFirestore.CodableBSONObjectId {}