AutoCat/AutoCatCore/Services/StorageService/StorageService.swift

54 lines
1.3 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
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 {
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)
}
}
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
}
}
}