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.
62 lines
1.8 KiB
62 lines
1.8 KiB
//
|
|
// PendingOperationManager.swift
|
|
// LeStorage
|
|
//
|
|
// Created by Laurent Morvillier on 01/04/2025.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
class PendingOperationManager<T: Storable> {
|
|
|
|
fileprivate(set) var items: [PendingOperation<T>] = []
|
|
|
|
fileprivate var _fileName: String = "pending_\(T.resourceName())"
|
|
|
|
fileprivate var _inMemory: Bool = false
|
|
|
|
init(store: Store, inMemory: Bool) {
|
|
self._inMemory = inMemory
|
|
if !inMemory {
|
|
do {
|
|
let url = try store.fileURL(fileName: self._fileName)
|
|
if FileManager.default.fileExists(atPath: url.path()) {
|
|
let jsonString = try FileUtils.readDocumentFile(fileName: self._fileName)
|
|
if let decoded: [PendingOperation<T>] = try jsonString.decode() {
|
|
self.items = decoded
|
|
}
|
|
}
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
}
|
|
}
|
|
|
|
func addPendingOperation(method: StorageMethod, instance: T, actionOption: ActionOption) {
|
|
Logger.log("addPendingOperation: \(method), \(instance)")
|
|
|
|
let operation = PendingOperation<T>(method: method, data: instance, actionOption: actionOption)
|
|
self.items.append(operation)
|
|
|
|
self._writeIfNecessary()
|
|
}
|
|
|
|
func reset() {
|
|
self.items.removeAll()
|
|
self._writeIfNecessary()
|
|
}
|
|
|
|
fileprivate func _writeIfNecessary() {
|
|
guard !self._inMemory else { return }
|
|
|
|
Task(priority: .background) {
|
|
do {
|
|
let jsonString: String = try self.items.jsonString()
|
|
let _ = try FileUtils.writeToDocumentDirectory(content: jsonString, fileName: self._fileName)
|
|
} catch {
|
|
Logger.error(error)
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|