JSONBridge.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 freeapsSettings(from: JSON) throws -> FreeAPSSettings {
  33. try JSONBridge.from(string: from.rawJSON)
  34. }
  35. static func from<T: Decodable>(string: String) throws -> T {
  36. guard let data = string.data(using: .utf8) else {
  37. throw JSONError.invalidString
  38. }
  39. return try JSONCoding.decoder.decode(T.self, from: data)
  40. }
  41. static func to<T: Encodable>(_ value: T) throws -> String {
  42. let data = try JSONCoding.encoder.encode(value)
  43. guard let string = String(data: data, encoding: .utf8) else {
  44. throw JSONError.encodingFailed
  45. }
  46. return string
  47. }
  48. }