58 lines
1.4 KiB
Swift
58 lines
1.4 KiB
Swift
import Foundation
|
|
import RealmSwift
|
|
|
|
protocol StorageServiceProtocol {
|
|
|
|
func store(vehicle: Vehicle) throws
|
|
}
|
|
|
|
public class StorageService: StorageServiceProtocol {
|
|
|
|
public enum StorageError: String, LocalizedError {
|
|
|
|
case openDatabaseError = "Ошибка открытия БД"
|
|
|
|
public var errorDescription: String? {
|
|
rawValue
|
|
}
|
|
}
|
|
|
|
private static var instance: StorageService?
|
|
|
|
private let realm: Realm
|
|
|
|
public static var shared: StorageService {
|
|
get throws {
|
|
if let instance = StorageService.instance {
|
|
return instance
|
|
} else {
|
|
if let service = StorageService(inMemory: Testing.isUITesting) {
|
|
StorageService.instance = service
|
|
return service
|
|
} else {
|
|
throw StorageError.openDatabaseError
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
init?(inMemory: Bool = false) {
|
|
let config = Realm.Configuration(inMemoryIdentifier: inMemory ? "memory" : nil)
|
|
|
|
guard let realm = try? Realm(configuration: config) else {
|
|
return nil
|
|
}
|
|
|
|
self.realm = realm
|
|
}
|
|
|
|
// MARK: - StorageServiceProtocol
|
|
|
|
public func store(vehicle: Vehicle) throws {
|
|
|
|
try realm.write {
|
|
realm.add(vehicle, update: .all)
|
|
}
|
|
}
|
|
}
|