// // GetUserUseCase.swift // Login // // Created by Javier Cicchelli on 12/12/2022. // Copyright © 2022 Röck+Cöde. All rights reserved. // import APIService import DataModels import DependencyInjection import Dependencies import KeychainStorage public actor GetUserUseCase { // MARK: Storages @KeychainStorage(key: .KeychainStorage.account) var account: Account? // MARK: Properties private let apiService: APIService // MARK: Initialisers public init(apiService: APIService) { self.apiService = apiService } // MARK: Functions public func callAsFunction() async throws -> User { guard let account else { throw GetUserError.accountNotFound } return try await getUser( username: account.username, password: account.password ) } public func callAsFunction( username: String, password: String ) async throws -> User { let user = try await getUser( username: username, password: password ) account = .init( username: username, password: password ) return user } } // MARK: - Initialisers public extension GetUserUseCase { init() { @Dependency(\.apiService) var apiService self.init(apiService: apiService) } } // MARK: - Helpers private extension GetUserUseCase { func getUser( username: String, password: String ) async throws -> User { let me = try await apiService.getUser( credentials: .init( username: username, password: password ) ) return .init( profile: .init( firstName: me.firstName, lastName: me.lastName ), rootFolder: .init( id: me.rootItem.id, name: me.rootItem.name, lastModifiedAt: me.rootItem.lastModifiedAt ) ) } } // MARK: - Errors public enum GetUserError: Error { case accountNotFound }