// // StorageService.swift // AutoCatCore // // Created by Selim Mustafaev on 22.06.2024. // Copyright © 2024 Selim Mustafaev. All rights reserved. // import Foundation import RealmSwift public enum StorageError: LocalizedError { case vehicleNotFound case noteNotFound public var errorDescription: String? { switch self { case .vehicleNotFound: "Vehicle not found in realm database" case .noteNotFound: "Vehicle note not found in realm database" } } } public actor StorageService: StorageServiceProtocol { private static var instance: StorageService? public static var shared: StorageService { get async throws { if let instance { return instance } else { let service = try await StorageService() instance = service return service } } } var realm: Realm! public init(config: Realm.Configuration = .defaultConfiguration) async throws { realm = try await Realm(configuration: config, actor: self) } public func updateVehicleIfExists(dto: VehicleDto) async throws { guard realm.object(ofType: Vehicle.self, forPrimaryKey: dto.getNumber()) != nil else { return } try await realm.asyncWrite { realm.add(Vehicle(dto: dto), update: .all) } } }