JSONImporter.swift 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. decoder.dateDecodingStrategy = .millisecondsSince1970
  34. return try decoder.decode(T.self, from: data)
  35. }
  36. /// Retrieves the set of dates for all glucose values currently stored in CoreData.
  37. ///
  38. /// - Returns: A set of dates corresponding to existing glucose readings.
  39. /// - Throws: An error if the fetch operation fails.
  40. private func fetchGlucoseDates() async throws -> Set<Date> {
  41. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  42. ofType: GlucoseStored.self,
  43. onContext: context,
  44. predicate: NSPredicate(format: "TRUEPREDICATE"),
  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) async throws {
  62. let glucoseHistory: [Glucose] = try readJsonFile(url: url)
  63. let existingDates = try await fetchGlucoseDates()
  64. for glucoseEntry in glucoseHistory {
  65. if !existingDates.contains(glucoseEntry.date) {
  66. try glucoseEntry.store(in: context)
  67. }
  68. }
  69. }
  70. }
  71. // MARK: - Extension for Specific Import Functions
  72. extension JSONImporter {
  73. func importGlucoseHistoryIfNeeded() async {}
  74. }