JSONBridge.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import Foundation
  2. enum JSONError: Error {
  3. case invalidString
  4. case invalidDate(String)
  5. case decodingFailed(Error)
  6. case encodingFailed
  7. }
  8. enum JSONBridge {
  9. static func preferences(from: JSON) throws -> Preferences {
  10. try JSONBridge.from(string: from.rawJSON)
  11. }
  12. static func pumpSettings(from: JSON) throws -> PumpSettings {
  13. try JSONBridge.from(string: from.rawJSON)
  14. }
  15. static func bgTargets(from: JSON) throws -> BGTargets {
  16. try JSONBridge.from(string: from.rawJSON)
  17. }
  18. static func basalProfile(from: JSON) throws -> [BasalProfileEntry] {
  19. try JSONBridge.from(string: from.rawJSON)
  20. }
  21. static func insulinSensitivities(from: JSON) throws -> InsulinSensitivities {
  22. try JSONBridge.from(string: from.rawJSON)
  23. }
  24. static func carbRatios(from: JSON) throws -> CarbRatios {
  25. try JSONBridge.from(string: from.rawJSON)
  26. }
  27. static func tempTargets(from: JSON) throws -> [TempTarget] {
  28. try JSONBridge.from(string: from.rawJSON)
  29. }
  30. static func model(from: JSON) -> String {
  31. from.rawJSON
  32. }
  33. static func trioSettings(from: JSON) throws -> TrioSettings {
  34. try JSONBridge.from(string: from.rawJSON)
  35. }
  36. static func pumpHistory(from: JSON) throws -> [PumpHistoryEvent] {
  37. try JSONBridge.from(string: from.rawJSON)
  38. }
  39. static func profile(from: JSON) throws -> Profile {
  40. try JSONBridge.from(string: from.rawJSON)
  41. }
  42. static func autosens(from: JSON) throws -> Autosens? {
  43. try JSONBridge.from(string: from.rawJSON)
  44. }
  45. static func clock(from: JSON) throws -> Date {
  46. let dateJson = from.rawJSON.replacingOccurrences(of: "\"", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
  47. if let date = Formatter.iso8601withFractionalSeconds.date(from: dateJson) ?? Formatter.iso8601
  48. .date(from: dateJson)
  49. {
  50. return date
  51. }
  52. throw JSONError.invalidDate(from.rawJSON)
  53. }
  54. static func from<T: Decodable>(string: String) throws -> T {
  55. guard let data = string.data(using: .utf8) else {
  56. throw JSONError.invalidString
  57. }
  58. return try JSONCoding.decoder.decode(T.self, from: data)
  59. }
  60. static func to<T: Encodable>(_ value: T) throws -> String {
  61. let data = try JSONCoding.encoder.encode(value)
  62. guard let string = String(data: data, encoding: .utf8) else {
  63. throw JSONError.encodingFailed
  64. }
  65. return string
  66. }
  67. }