Auto get from server if file does not exists

multistore
Laurent 2 years ago
parent cab41af854
commit de5d39cc90
  1. 2
      LeStorage/Services.swift
  2. 8
      LeStorage/Store.swift
  3. 21
      LeStorage/StoredCollection.swift

@ -37,7 +37,7 @@ class Services {
// MARK: - Base
fileprivate func runRequest<T : Decodable>(_ request: URLRequest, apiCallId: String? = nil) async throws -> T {
Logger.log("Run request...")
Logger.log("Run \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "")")
let task: (Data, URLResponse) = try await URLSession.shared.data(for: request)
if let response = task.1 as? HTTPURLResponse {
let statusCode = response.statusCode

@ -12,6 +12,7 @@ enum StoreError: Error {
case unexpectedCollectionType(name: String)
case apiCallCollectionNotRegistered(type: String)
case collectionNotRegistered(type: String)
case unSynchronizedCollection
}
public class Store {
@ -167,4 +168,11 @@ public class Store {
_ = try await self._executeApiCall(apiCall)
}
func getItems<T : Storable>() async throws -> [T] {
guard let service else {
throw StoreError.missingService
}
return try await service.get()
}
}

@ -23,7 +23,11 @@ public class StoredCollection<T : Storable> : RandomAccessCollection, SomeCollec
let synchronized: Bool
/// The list of stored items
@Published public fileprivate(set) var items: [T] = []
@Published public fileprivate(set) var items: [T] = [] {
didSet {
self._hasChanged = true
}
}
/// The reference to the Store
fileprivate var _store: Store
@ -61,6 +65,8 @@ public class StoredCollection<T : Storable> : RandomAccessCollection, SomeCollec
let url = try FileUtils.directoryURLForFileName(self._fileName)
if FileManager.default.fileExists(atPath: url.path()) {
self._loadAsync()
} else {
try? self.loadDataFromServer()
}
} catch {
Logger.log(error)
@ -89,6 +95,19 @@ public class StoredCollection<T : Storable> : RandomAccessCollection, SomeCollec
}
public func loadDataFromServer() throws {
guard self.synchronized else {
throw StoreError.unSynchronizedCollection
}
Task {
do {
self.items = try await self._store.getItems()
} catch {
Logger.error(error)
}
}
}
/// Adds or updates the provided instance inside the collection
/// Adds it if its id is not found, and otherwise updates it
public func addOrUpdate(instance: T) {

Loading…
Cancel
Save