JSONImporter.swift 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import CoreData
  2. import Foundation
  3. /// Migration-specific errors that might happen during migration
  4. enum JSONImporterError: Error {
  5. case missingGlucoseValueInGlucoseEntry
  6. }
  7. // MARK: - JSONImporter Class
  8. /// Responsible for importing JSON data into Core Data.
  9. ///
  10. /// The importer handles two important states:
  11. /// - JSON files stored in the file system that contain data to import
  12. /// - Existing entries in CoreData that should not be duplicated
  13. ///
  14. /// Imports are performed when a JSON file exists. The importer checks
  15. /// CoreData for existing entries to avoid duplicating records from partial imports.
  16. class JSONImporter {
  17. private let context: NSManagedObjectContext
  18. private let coreDataStack: CoreDataStack
  19. /// Initializes the importer with a Core Data context.
  20. init(context: NSManagedObjectContext, coreDataStack: CoreDataStack) {
  21. self.context = context
  22. self.coreDataStack = coreDataStack
  23. }
  24. /// Reads and parses a JSON file from the file system.
  25. ///
  26. /// - Parameters:
  27. /// - url: The URL of the JSON file to read.
  28. /// - Returns: A decoded object of the specified type.
  29. /// - Throws: An error if the file cannot be read or decoded.
  30. private func readJsonFile<T: Decodable>(url: URL) throws -> T {
  31. let data = try Data(contentsOf: url)
  32. let decoder = JSONCoding.decoder
  33. return try decoder.decode(T.self, from: data)
  34. }
  35. /// Retrieves the set of dates for all glucose values currently stored in CoreData.
  36. ///
  37. /// - Returns: A set of dates corresponding to existing glucose readings.
  38. /// - Throws: An error if the fetch operation fails.
  39. private func fetchGlucoseDates() async throws -> Set<Date> {
  40. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  41. ofType: GlucoseStored.self,
  42. onContext: context,
  43. predicate: NSPredicate(format: "TRUEPREDICATE"),
  44. key: "date",
  45. ascending: false
  46. ) as? [GlucoseStored] ?? []
  47. return Set(allReadings.compactMap(\.date))
  48. }
  49. /// Imports glucose history from a JSON file into CoreData.
  50. ///
  51. /// The function reads glucose data from the provided JSON file and stores new entries
  52. /// in CoreData, skipping entries with dates that already exist in the database.
  53. ///
  54. /// - Parameters:
  55. /// - url: The URL of the JSON file containing glucose history.
  56. /// - Throws:
  57. /// - JSONImporterError.missingGlucoseValueInGlucoseEntry if a glucose entry is missing a value.
  58. /// - An error if the file cannot be read or decoded.
  59. /// - An error if the CoreData operation fails.
  60. func importGlucoseHistory(url: URL) async throws {
  61. let glucoseHistory: [BloodGlucose] = try readJsonFile(url: url)
  62. let existingDates = try await fetchGlucoseDates()
  63. for glucoseEntry in glucoseHistory {
  64. if !existingDates.contains(glucoseEntry.dateString) {
  65. try glucoseEntry.store(in: context)
  66. }
  67. }
  68. }
  69. }
  70. // MARK: - Extension for Specific Import Functions
  71. extension BloodGlucose {
  72. func store(in context: NSManagedObjectContext) throws {
  73. guard let glucoseValue = glucose ?? sgv else {
  74. throw JSONImporterError.missingGlucoseValueInGlucoseEntry
  75. }
  76. let glucoseEntry = GlucoseStored(context: context)
  77. glucoseEntry.id = _id.flatMap({ UUID(uuidString: $0) }) ?? UUID()
  78. glucoseEntry.date = dateString
  79. glucoseEntry.glucose = Int16(glucoseValue)
  80. glucoseEntry.direction = direction?.rawValue
  81. glucoseEntry.isManual = type == "Manual"
  82. glucoseEntry.isUploadedToNS = true
  83. glucoseEntry.isUploadedToHealth = true
  84. glucoseEntry.isUploadedToTidepool = true
  85. }
  86. }
  87. extension JSONImporter {
  88. func importGlucoseHistoryIfNeeded() async {}
  89. }