先上结果
let configuration = DFDataFile(folder: filePath.projects(), name: "configuration.json")
.codable(Configuration.self)
let indexDB = DFDataFile(folder: filePath.projects(), name: "index.db")
.compression(.zlib)
.codable(IndexDB.self)
代码实现
import Foundation
import STFilePath
public protocol DownloadableFile: Sendable {
associatedtype Model: Sendable
typealias FetchTransform<To: Sendable> = @Sendable (_ model: Model) async throws -> To
typealias SaveTransform<To: Sendable> = @Sendable (_ model: To) async throws -> Model
func fetch() async throws -> Model
func save(_ model: Model?) async throws
}
public extension DownloadableFile {
func map<To: Sendable>(
fetch: @escaping FetchTransform<To>,
save: @escaping SaveTransform<To>
) -> DKFileMap<Self, To> {
DKFileMap(file: self, fetch: fetch, save: save)
}
func compression(_ algorithm: STComparator.Algorithm) -> DKFileMap<Self, Data> where Model == Data {
self.map { model in
try STComparator.decompress(model, algorithm: algorithm)
} save: { model in
try STComparator.compress(model, algorithm: algorithm)
}
}
func codable<Kind: Codable>(
_ kind: Kind.Type,
encoder: JSONEncoder,
decoder: JSONDecoder
) -> DKFileMap<Self, Kind> where Model == Data {
self.map { model in
try decoder.decode(kind.self, from: model)
} save: { model in
try encoder.encode(model)
}
}
func codable<Kind: Codable>(
_ kind: Kind.Type,
encoderOutputFormatting: JSONEncoder.OutputFormatting = [.prettyPrinted, .sortedKeys]
) -> DKFileMap<Self, Kind> where Model == Data {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = encoderOutputFormatting
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .iso8601
return self.codable(kind, encoder: encoder, decoder: decoder)
}
}
public struct DFDataFile: Sendable, DownloadableFile {
public var file: any AnyFile
public init(file: any AnyFile) {
self.file = file
}
public init(folder: any AnyFolder, name: String) {
self.init(file: folder.file(name))
}
public func fetch() async throws -> Data {
try await file.data()
}
public func save(_ model: Data?) async throws {
try await file.overlay(with: model, options: .init())
}
}
public struct DKFileMap<DKFile: DownloadableFile, To: Sendable>: Sendable, DownloadableFile {
public typealias Model = To
public let file: DKFile
public let fetchTransform: DKFile.FetchTransform<To>
public let saveTransform: DKFile.SaveTransform<To>
public init(
file: DKFile,
fetch: @escaping DKFile.FetchTransform<To>,
save: @escaping DKFile.SaveTransform<To>
) {
self.file = file
self.fetchTransform = fetch
self.saveTransform = save
}
public func fetch() async throws -> To {
let data = try await file.fetch()
return try await fetchTransform(data)
}
public func save(_ model: To?) async throws {
if let model = model {
let data = try await saveTransform(model)
try await file.save(data)
} else {
try await file.save(nil)
}
}
}