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.
61 lines
1.8 KiB
61 lines
1.8 KiB
//
|
|
// StoredObject.swift
|
|
// LeStorage
|
|
//
|
|
// Created by Laurent Morvillier on 03/05/2024.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
/// A class extending the capabilities of StoredCollection but supposedly manages only one item
|
|
public class StoredSingleton<T: SyncedStorable>: SyncedCollection<T> {
|
|
|
|
var shouldLoadDataFromServer: Bool = true
|
|
|
|
init(store: Store, inMemory: Bool = false, shouldLoadDataFromServer: Bool = true) {
|
|
super.init(store: store, inMemory: inMemory)
|
|
self.shouldLoadDataFromServer = shouldLoadDataFromServer
|
|
}
|
|
|
|
public override func loadDataFromServerIfAllowed(clear: Bool = false) async throws {
|
|
if shouldLoadDataFromServer {
|
|
try await super.loadDataFromServerIfAllowed(clear: clear)
|
|
}
|
|
}
|
|
|
|
/// Sets the singleton to the collection without synchronizing it
|
|
public func setItemNoSync(_ instance: T) {
|
|
self.collection.setSingletonNoSync(instance: instance)
|
|
}
|
|
|
|
/// updates the existing singleton
|
|
public func update() {
|
|
if let item = self.item() {
|
|
self.addOrUpdate(instance: item)
|
|
}
|
|
}
|
|
|
|
/// Returns the singleton
|
|
public func item() -> T? {
|
|
return self.collection.items.first
|
|
}
|
|
|
|
public func tryPutBeforeUpdating(_ instance: T) async throws {
|
|
let result = try await StoreCenter.main.service().rawPut(instance)
|
|
if let item = self.item() {
|
|
item.copy(from: result)
|
|
self.addOrUpdate(instance: item)
|
|
}
|
|
}
|
|
|
|
// MARK: - Protects from use
|
|
|
|
public override func addOrUpdate(contentOfs sequence: any Sequence<T>) {
|
|
fatalError("method unavailable for StoredSingleton, use update")
|
|
}
|
|
|
|
func addOrUpdateIfNewer(_ instance: T) {
|
|
fatalError("method unavailable for StoredSingleton, use update")
|
|
}
|
|
|
|
}
|
|
|