73 lines
1.9 KiB
Swift
73 lines
1.9 KiB
Swift
//
|
|
// 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
|
|
case eventNotFound
|
|
|
|
public var errorDescription: String? {
|
|
switch self {
|
|
case .vehicleNotFound: "Vehicle not found in realm database"
|
|
case .noteNotFound: "Vehicle note not found in realm database"
|
|
case .eventNotFound: "Event not found in realm database"
|
|
}
|
|
}
|
|
}
|
|
|
|
public actor StorageService: StorageServiceProtocol {
|
|
|
|
let settingsService: SettingsServiceProtocol
|
|
|
|
var realm: Realm!
|
|
|
|
public init(settingsService: SettingsServiceProtocol,
|
|
config: Realm.Configuration = .defaultConfiguration) async throws {
|
|
|
|
self.settingsService = settingsService
|
|
realm = try await Realm(configuration: config, actor: self)
|
|
}
|
|
|
|
public var dbFileURL: URL? {
|
|
get async {
|
|
realm.configuration.fileURL
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
public func loadVehicle(number: String) async throws -> VehicleDto {
|
|
|
|
if let vehicle = realm.object(ofType: Vehicle.self, forPrimaryKey: number) {
|
|
return vehicle.dto
|
|
} else {
|
|
throw StorageError.vehicleNotFound
|
|
}
|
|
}
|
|
|
|
public func loadVehicles() async -> [VehicleDto] {
|
|
|
|
realm.objects(Vehicle.self)
|
|
.sorted(byKeyPath: "updatedDate", ascending: false)
|
|
.map(\.shallowDto)
|
|
}
|
|
}
|