Codable.swift 2.5 KB

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