Codable.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2021 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 FirebaseRemoteConfig
  18. import FirebaseSharedSwift
  19. public enum RemoteConfigValueCodableError: Error {
  20. case unsupportedType(String)
  21. }
  22. public extension RemoteConfigValue {
  23. /// Extracts a RemoteConfigValue JSON-encoded object and decodes it to the requested type.
  24. ///
  25. /// - Parameter asType: The type to decode the JSON-object to
  26. func decoded<Value: Decodable>(asType: Value.Type = Value.self) throws -> Value {
  27. if asType == Date.self {
  28. throw RemoteConfigValueCodableError
  29. .unsupportedType("Date type is not currently supported for " +
  30. " Remote Config Value decoding. Please file a feature request")
  31. }
  32. return try FirebaseDataDecoder()
  33. .decode(Value.self, from: FirebaseRemoteConfigValueDecoderHelper(value: self))
  34. }
  35. }
  36. public enum RemoteConfigCodableError: Error {
  37. case invalidSetDefaultsInput(String)
  38. }
  39. public extension RemoteConfig {
  40. /// Decodes a struct from the respective Remote Config values.
  41. ///
  42. /// - Parameter asType: The type to decode to.
  43. func decoded<Value: Decodable>(asType: Value.Type = Value.self) throws -> Value {
  44. let keys = allKeys(from: RemoteConfigSource.default) + allKeys(from: RemoteConfigSource.remote)
  45. let config = keys.reduce(into: [String: FirebaseRemoteConfigValueDecoderHelper]()) {
  46. $0[$1] = FirebaseRemoteConfigValueDecoderHelper(value: configValue(forKey: $1))
  47. }
  48. return try FirebaseDataDecoder().decode(Value.self, from: config)
  49. }
  50. /// Sets config defaults from an encodable struct.
  51. ///
  52. /// - Parameter value: The object to use to set the defaults.
  53. func setDefaults<Value: Encodable>(from value: Value) throws {
  54. guard let encoded = try FirebaseDataEncoder().encode(value) as? [String: NSObject] else {
  55. throw RemoteConfigCodableError.invalidSetDefaultsInput(
  56. "The setDefaults input: \(value), must be a Struct that encodes to a Dictionary"
  57. )
  58. }
  59. setDefaults(encoded)
  60. }
  61. }