JSONBridge.swift 1.9 KB

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