AutoCat/AutoCatCore/Services/StorageService/StorageService.swift

83 lines
2.1 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
}
}
@discardableResult
public func updateVehicle(dto: VehicleDto, policy: DbUpdatePolicy) async throws -> Bool {
let shouldUpdate = switch policy {
case .always:
true
case .ifExists:
realm.object(ofType: Vehicle.self, forPrimaryKey: dto.getNumber()) != nil
}
guard shouldUpdate else {
return false
}
try await realm.asyncWrite {
realm.add(Vehicle(dto: dto), update: .all)
}
return true
}
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)
}
}