diff --git a/LeStorage/Store.swift b/LeStorage/Store.swift index cb29b78..5577ffd 100644 --- a/LeStorage/Store.swift +++ b/LeStorage/Store.swift @@ -43,7 +43,7 @@ final public class Store { static let storageDirectory = "storage" /// The store identifier, used to name the store directory, and to perform filtering requests to the server - fileprivate(set) var identifier: String? = nil + public fileprivate(set) var identifier: String? = nil /// Indicates whether the store directory has been created at the init fileprivate var _created: Bool = false @@ -76,6 +76,10 @@ final public class Store { /// - inMemory: Indicates if the collection should only live in memory, and not write into a file public func registerCollection(indexed: Bool = false, inMemory: Bool = false) -> StoredCollection { + if let collection: StoredCollection = try? self.collection() { + return collection + } + let collection = StoredCollection(store: self, indexed: indexed, inMemory: inMemory) self._collections[T.resourceName()] = collection @@ -88,11 +92,13 @@ final public class Store { /// - inMemory: Indicates if the collection should only live in memory, and not write into a file public func registerSynchronizedCollection(indexed: Bool = false, inMemory: Bool = false) -> StoredCollection { + if let collection: StoredCollection = try? self.collection() { + return collection + } + let collection = StoredCollection(store: self, indexed: indexed, inMemory: inMemory) self._collections[T.resourceName()] = collection - StoreCenter.main.loadApiCallCollection(type: T.self) - return collection } @@ -145,13 +151,11 @@ final public class Store { throw StoreError.collectionNotRegistered(type: T.resourceName()) } - subscript(_ type: T.Type) -> StoredCollection { - get { - do { - return try self.collection() - } catch { - fatalError(error.localizedDescription) - } + func registerOrGetSyncedCollection(_ type: T.Type) -> StoredCollection { + do { + return try self.collection() + } catch { + return self.registerSynchronizedCollection(indexed: true, inMemory: false) } } @@ -197,12 +201,8 @@ final public class Store { /// Calls addOrUpdateIfNewer from the collection corresponding to the instance func addOrUpdateIfNewer(_ instance: T) { - do { - let collection: StoredCollection = try self.collection() - collection.addOrUpdateIfNewer(instance) - } catch { - Logger.error(error) - } + let collection: StoredCollection = self.registerOrGetSyncedCollection(T.self) + collection.addOrUpdateIfNewer(instance) } /// Calls deleteById from the collection corresponding to the instance