JSONImporter.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. /// - Parameters: the start and end dates to fetch glucose values, inclusive
  38. /// - Returns: A set of dates corresponding to existing glucose readings.
  39. /// - Throws: An error if the fetch operation fails.
  40. private func fetchGlucoseDates(start: Date, end: Date) async throws -> Set<Date> {
  41. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  42. ofType: GlucoseStored.self,
  43. onContext: context,
  44. predicate: .predicateForDateBetween(start: start, end: end),
  45. key: "date",
  46. ascending: false
  47. ) as? [GlucoseStored] ?? []
  48. return Set(allReadings.compactMap(\.date))
  49. }
  50. /// Imports glucose history from a JSON file into CoreData.
  51. ///
  52. /// The function reads glucose data from the provided JSON file and stores new entries
  53. /// in CoreData, skipping entries with dates that already exist in the database.
  54. ///
  55. /// - Parameters:
  56. /// - url: The URL of the JSON file containing glucose history.
  57. /// - Throws:
  58. /// - JSONImporterError.missingGlucoseValueInGlucoseEntry if a glucose entry is missing a value.
  59. /// - An error if the file cannot be read or decoded.
  60. /// - An error if the CoreData operation fails.
  61. func importGlucoseHistory(url: URL, now: Date) async throws {
  62. let twentyFourHoursAgo = now - 24.hours.timeInterval
  63. let glucoseHistoryFull: [BloodGlucose] = try readJsonFile(url: url)
  64. let existingDates = try await fetchGlucoseDates(start: twentyFourHoursAgo, end: now)
  65. // only import glucose values from the last 24 hours that don't exist
  66. let glucoseHistory = glucoseHistoryFull
  67. .filter { $0.dateString >= twentyFourHoursAgo && $0.dateString <= now && !existingDates.contains($0.dateString) }
  68. // Create a background context for batch processing
  69. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  70. backgroundContext.parent = context
  71. try await backgroundContext.perform {
  72. for glucoseEntry in glucoseHistory {
  73. try glucoseEntry.store(in: backgroundContext)
  74. }
  75. try backgroundContext.save()
  76. }
  77. try await context.perform {
  78. try self.context.save()
  79. }
  80. }
  81. }
  82. // MARK: - Extension for Specific Import Functions
  83. extension BloodGlucose {
  84. /// Helper function to convert `BloodGlucose` to `GlucoseStored` while importing JSON glucose entries
  85. func store(in context: NSManagedObjectContext) throws {
  86. guard let glucoseValue = glucose ?? sgv else {
  87. throw JSONImporterError.missingGlucoseValueInGlucoseEntry
  88. }
  89. let glucoseEntry = GlucoseStored(context: context)
  90. glucoseEntry.id = _id.flatMap({ UUID(uuidString: $0) }) ?? UUID()
  91. glucoseEntry.date = dateString
  92. glucoseEntry.glucose = Int16(glucoseValue)
  93. glucoseEntry.direction = direction?.rawValue
  94. glucoseEntry.isManual = type == "Manual"
  95. glucoseEntry.isUploadedToNS = true
  96. glucoseEntry.isUploadedToHealth = true
  97. glucoseEntry.isUploadedToTidepool = true
  98. }
  99. }
  100. extension JSONImporter {
  101. func importGlucoseHistoryIfNeeded() async {}
  102. }