From c25ca4cf0fade840f9399614696ccb84a4a3f7e0 Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Sun, 18 Dec 2022 16:12:09 +0100 Subject: [PATCH] Improved the GetUserUseCase use case by moving some logic to this use case. --- .../UseCases/Users/GetUserUseCase.swift | 69 +++++++++++++++++-- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/Libraries/Sources/UseCases/Users/GetUserUseCase.swift b/Libraries/Sources/UseCases/Users/GetUserUseCase.swift index e06aeae..fe2eaed 100644 --- a/Libraries/Sources/UseCases/Users/GetUserUseCase.swift +++ b/Libraries/Sources/UseCases/Users/GetUserUseCase.swift @@ -10,22 +10,76 @@ import APIService import DataModels import DependencyInjection import Dependencies +import KeychainStorage -public struct GetUserUseCase { +public actor GetUserUseCase { - // MARK: Dependencies + // MARK: Properties - @Dependency(\.apiService) private var apiService + private let apiService: APIService + + private var account: Account? // MARK: Initialisers - public init() {} + public init( + apiService: APIService, + account: Account? + ) { + self.apiService = apiService + self.account = account + } // 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 + @KeychainStorage(key: .KeychainStorage.account) var account: Account? + + self.init( + apiService: apiService, + account: account + ) + } +} + +// MARK: - Helpers + +private extension GetUserUseCase { + func getUser( + username: String, + password: String ) async throws -> User { let me = try await apiService.getUser( credentials: .init( @@ -46,5 +100,10 @@ public struct GetUserUseCase { ) ) } - +} + +// MARK: - Errors + +public enum GetUserError: Error { + case accountNotFound }