diff --git a/Modules/Sources/Browse/Logic/Adapters/FileAdapter.swift b/Modules/Sources/Browse/Logic/Adapters/FileAdapter.swift new file mode 100644 index 0000000..ff768fe --- /dev/null +++ b/Modules/Sources/Browse/Logic/Adapters/FileAdapter.swift @@ -0,0 +1,41 @@ +// +// FileAdapter.swift +// Browse +// +// Created by Javier Cicchelli on 17/12/2022. +// Copyright © 2022 Röck+Cöde. All rights reserved. +// + +import APIService +import Foundation + +struct FileAdapter { + func callAsFunction(url: URL) throws -> File { + guard url.isFileURL else { + throw FileAdapterError.urlIsNotFileURL + } + + let data = try Data(contentsOf: url) + let name = try url + .resourceValues(forKeys: [.nameKey]) + .allValues + .first(where: { $0.key == .nameKey }) + .map(\.value) + + guard let name = name as? String else { + throw FileAdapterError.nameNotCasted + } + + return .init( + name: name, + data: data + ) + } +} + +// MARK: - Errors + +enum FileAdapterError: Error { + case urlIsNotFileURL + case nameNotCasted +} diff --git a/Modules/Sources/Browse/Logic/Use Cases/UploadFileUseCase.swift b/Modules/Sources/Browse/Logic/Use Cases/UploadFileUseCase.swift new file mode 100644 index 0000000..8a82025 --- /dev/null +++ b/Modules/Sources/Browse/Logic/Use Cases/UploadFileUseCase.swift @@ -0,0 +1,50 @@ +// +// UploadFileUseCase.swift +// Browse +// +// Created by Javier Cicchelli on 17/12/2022. +// Copyright © 2022 Röck+Cöde. All rights reserved. +// + +import APIService +import DependencyInjection +import Dependencies +import Foundation + +struct UploadFileUseCase { + + // MARK: Properties + + let apiService: APIService + + private let fileAdapter: FileAdapter = .init() + + // MARK: Functions + + func callAsFunction( + id: String, + url: URL, + username: String, + password: String + ) async throws { + _ = try await apiService.uploadFile( + id: id, + file: fileAdapter(url: url), + credentials: .init( + username: username, + password: password + ) + ) + } + +} + +// MARK: - Initialisers + +extension UploadFileUseCase { + init() { + @Dependency(\.apiService) var apiService + + self.init(apiService: apiService) + } +}