JSONBridge.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import Foundation
  2. enum JSONError: Error {
  3. case invalidString
  4. case decodingFailed(Error)
  5. case encodingFailed
  6. }
  7. enum JSONBridge {
  8. static func preferences(from: JSON) throws -> Preferences {
  9. try JSONBridge.from(string: from.rawJSON)
  10. }
  11. static func pumpSettings(from: JSON) throws -> PumpSettings {
  12. try JSONBridge.from(string: from.rawJSON)
  13. }
  14. static func bgTargets(from: JSON) throws -> BGTargets {
  15. try JSONBridge.from(string: from.rawJSON)
  16. }
  17. static func basalProfile(from: JSON) throws -> [BasalProfileEntry] {
  18. try JSONBridge.from(string: from.rawJSON)
  19. }
  20. static func insulinSensitivities(from: JSON) throws -> InsulinSensitivities {
  21. try JSONBridge.from(string: from.rawJSON)
  22. }
  23. static func carbRatios(from: JSON) throws -> CarbRatios {
  24. try JSONBridge.from(string: from.rawJSON)
  25. }
  26. static func tempTargets(from: JSON) throws -> [TempTarget] {
  27. try JSONBridge.from(string: from.rawJSON)
  28. }
  29. static func model(from: JSON) -> String {
  30. from.rawJSON
  31. }
  32. static func autotune(from: JSON) throws -> Autotune? {
  33. guard from.rawJSON != RawJSON.null else { return nil }
  34. return try JSONBridge.from(string: from.rawJSON)
  35. }
  36. static func freeapsSettings(from: JSON) throws -> FreeAPSSettings {
  37. try JSONBridge.from(string: from.rawJSON)
  38. }
  39. static func from<T: Decodable>(string: String) throws -> T {
  40. guard let data = string.data(using: .utf8) else {
  41. throw JSONError.invalidString
  42. }
  43. return try JSONCoding.decoder.decode(T.self, from: data)
  44. }
  45. static func to<T: Encodable>(_ value: T) throws -> String {
  46. let data = try JSONCoding.encoder.encode(value)
  47. guard let string = String(data: data, encoding: .utf8) else {
  48. throw JSONError.encodingFailed
  49. }
  50. return string
  51. }
  52. }