Implemented the "createFile(at: with: )" function for the FileService service in the library target.

This commit is contained in:
2025-02-07 21:50:50 +01:00
parent 3dcb110de1
commit 33ae67fc58
5 changed files with 78 additions and 9 deletions
@@ -9,6 +9,7 @@ public protocol FileServicing {
// MARK: Functions
func copyFile(from source: URL, to destination: URL) async throws (FileServiceError)
func createFile(at location: URL, with data: Data) async throws (FileServiceError)
func createFolder(at location: URL) async throws (FileServiceError)
func deleteItem(at location: URL) async throws (FileServiceError)
func isItemExists(at location: URL) async throws (FileServiceError) -> Bool
@@ -18,6 +19,8 @@ public protocol FileServicing {
// MARK: - Errors
public enum FileServiceError: Error, Equatable {
case fileDataIsEmpty
case fileNotCreated
case folderNotCreated
case itemAlreadyExists
case itemEmptyData
@@ -30,7 +30,7 @@ extension FileService: FileServicing {
public func copyFile(from source: URL, to destination: URL) async throws (FileServiceError) {
guard try await !isItemExists(at: destination) else {
throw FileServiceError.itemAlreadyExists
throw .itemAlreadyExists
}
var itemData: Data?
@@ -38,43 +38,59 @@ extension FileService: FileServicing {
do {
itemData = try Data(contentsOf: source)
} catch {
throw FileServiceError.itemEmptyData
throw .itemEmptyData
}
do {
try itemData?.write(to: destination, options: .atomic)
} catch {
throw FileServiceError.itemNotCopied
throw .itemNotCopied
}
}
public func createFile(at location: URL, with data: Data) async throws (FileServiceError) {
guard try await !isItemExists(at: location) else {
throw .itemAlreadyExists
}
guard !data.isEmpty else {
throw .fileDataIsEmpty
}
do {
try data.write(to: location, options: .atomic)
} catch {
throw .fileNotCreated
}
}
public func createFolder(at location: URL) async throws (FileServiceError) {
guard try await !isItemExists(at: location) else {
throw FileServiceError.itemAlreadyExists
throw .itemAlreadyExists
}
do {
try fileManager.createDirectory(at: location, withIntermediateDirectories: true)
} catch {
throw FileServiceError.folderNotCreated
throw .folderNotCreated
}
}
public func deleteItem(at location: URL) async throws (FileServiceError) {
guard try await isItemExists(at: location) else {
throw FileServiceError.itemNotExists
throw .itemNotExists
}
do {
try fileManager.removeItem(at: location)
} catch {
throw FileServiceError.itemNotDeleted
throw .itemNotDeleted
}
}
public func isItemExists(at location: URL) async throws (FileServiceError) -> Bool {
guard location.isFileURL else {
throw FileServiceError.itemNotFileURL
throw .itemNotFileURL
}
let filePath = location.pathString