Created
November 24, 2021 19:43
-
-
Save vikingosegundo/a0487f1e228787546ec0ba8d1e71e893 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation.NSFileManager | |
func createDiskStore( | |
pathInDocs p: String = "state.json", | |
fileManager fm: FileManager = .default | |
) -> Store | |
{ | |
var state = loadAppStateFromStore(pathInDocuments: p, fileManager: fm) { didSet { callbacks.forEach { $0() } } } | |
var callbacks: [() -> ()] = [] | |
return ( | |
state : { state }, | |
change : { state = change(state, $0); persistStore(pathInDocuments: p, state: state, fileManager: fm) }, | |
reset : { state = AppState() ; persistStore(pathInDocuments: p, state: state, fileManager: fm) }, | |
updated : { callbacks = callbacks + [$0] }, | |
destroy : { destroyStore(pathInDocuments: p, fileManager: fm) } | |
) | |
} | |
//MARK: - | |
private func persistStore(pathInDocuments: String, state: AppState, fileManager: FileManager ) { | |
do { | |
let encoder = JSONEncoder() | |
#if DEBUG | |
encoder.outputFormatting = .prettyPrinted | |
#endif | |
let data = try encoder.encode(state) | |
try data.write(to: fileURL(pathInDocuments: pathInDocuments, fileManager: fileManager)) | |
} catch { print(error) } | |
} | |
private func loadAppStateFromStore(pathInDocuments: String, fileManager: FileManager) -> AppState { | |
do { | |
return try JSONDecoder().decode(AppState.self, from: try Data(contentsOf: fileURL(pathInDocuments: pathInDocuments, fileManager: fileManager))) | |
} catch { | |
print(error) | |
return AppState() | |
} | |
} | |
private func destroyStore(pathInDocuments: String, fileManager: FileManager) { | |
try? fileManager.removeItem(at: try! fileURL(pathInDocuments: pathInDocuments)) | |
} | |
private func fileURL(pathInDocuments: String, fileManager: FileManager = .default) throws -> URL { | |
try fileManager | |
.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) | |
.appendingPathComponent(pathInDocuments) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment