diff --git a/LeStorage/Services.swift b/LeStorage/Services.swift index 8c0f843..3e2ffb9 100644 --- a/LeStorage/Services.swift +++ b/LeStorage/Services.swift @@ -37,7 +37,7 @@ class Services { // MARK: - Base fileprivate func runRequest(_ 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 diff --git a/LeStorage/Store.swift b/LeStorage/Store.swift index ef1f024..436fcf0 100644 --- a/LeStorage/Store.swift +++ b/LeStorage/Store.swift @@ -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() async throws -> [T] { + guard let service else { + throw StoreError.missingService + } + return try await service.get() + } + } diff --git a/LeStorage/StoredCollection.swift b/LeStorage/StoredCollection.swift index 78bd42f..1c885c6 100644 --- a/LeStorage/StoredCollection.swift +++ b/LeStorage/StoredCollection.swift @@ -23,7 +23,11 @@ public class StoredCollection : 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 : 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 : 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) {