You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
2.5 KiB
100 lines
2.5 KiB
//
|
|
// StoredItem.swift
|
|
// LeStorage
|
|
//
|
|
// Created by Laurent Morvillier on 14/02/2024.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
public protocol MicroStorable : Codable {
|
|
init()
|
|
// static var fileName: String { get }
|
|
}
|
|
|
|
public class MicroStorage<T : MicroStorable> {
|
|
|
|
public fileprivate(set) var item: T
|
|
|
|
fileprivate var _fileName: String
|
|
|
|
public init(fileName: String) {
|
|
self._fileName = fileName
|
|
var instance: T? = nil
|
|
do {
|
|
let url = try FileUtils.pathForFileInDocumentDirectory(fileName)
|
|
if FileManager.default.fileExists(atPath: url.path()) {
|
|
let jsonString = try FileUtils.readDocumentFile(fileName: fileName)
|
|
if let decoded: T = try jsonString.decode() {
|
|
instance = decoded
|
|
}
|
|
}
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
|
|
self.item = instance ?? T()
|
|
}
|
|
|
|
public func update(handler: (T) -> ()) {
|
|
handler(self.item)
|
|
self.write()
|
|
}
|
|
|
|
public func write() {
|
|
do {
|
|
let jsonString: String = try self.item.jsonString()
|
|
let _ = try FileUtils.writeToDocumentDirectory(content: jsonString, fileName: self._fileName)
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
public class OptionalStorage<T : Codable> {
|
|
|
|
public var item: T? = nil {
|
|
didSet {
|
|
self._write()
|
|
}
|
|
}
|
|
|
|
fileprivate var _fileName: String
|
|
|
|
public init(fileName: String) {
|
|
self._fileName = fileName
|
|
do {
|
|
let url = try FileUtils.pathForFileInDocumentDirectory(fileName)
|
|
if FileManager.default.fileExists(atPath: url.path) {
|
|
let jsonString = try FileUtils.readDocumentFile(fileName: fileName)
|
|
if let decoded: T = try jsonString.decode() {
|
|
self.item = decoded
|
|
// Logger.log("user loaded with: \(jsonString)")
|
|
}
|
|
}
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
}
|
|
|
|
fileprivate func _write() {
|
|
|
|
var content = ""
|
|
if let item = self.item {
|
|
do {
|
|
content = try item.jsonString()
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
}
|
|
|
|
do {
|
|
let _ = try FileUtils.writeToDocumentDirectory(content: content, fileName: self._fileName)
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|