diff --git a/LeStorage/Store.swift b/LeStorage/Store.swift index e7a9ba9..e8130d0 100644 --- a/LeStorage/Store.swift +++ b/LeStorage/Store.swift @@ -64,10 +64,10 @@ public class Store { /// Registers a collection /// [synchronize] denotes a collection which modification will be sent to the django server - public func registerCollection(synchronized: Bool) -> StoredCollection { + public func registerCollection(synchronized: Bool, indexed: Bool = false) -> StoredCollection { // register collection - let collection = StoredCollection(synchronized: synchronized, store: Store.main, loadCompletion: nil) + let collection = StoredCollection(synchronized: synchronized, store: Store.main, indexed: indexed, loadCompletion: nil) self._collections[T.resourceName()] = collection // if synchronized { // register additional collection for api calls diff --git a/LeStorage/StoredCollection.swift b/LeStorage/StoredCollection.swift index 0904ece..9577538 100644 --- a/LeStorage/StoredCollection.swift +++ b/LeStorage/StoredCollection.swift @@ -179,14 +179,22 @@ public class StoredCollection: RandomAccessCollection, SomeCollecti } /// Inserts the whole sequence into the items array, no updates - public func append(contentOfs sequence: any Sequence) throws { + public func addOrUpdate(contentOfs sequence: any Sequence) throws { defer { self._hasChanged = true } - self.items.append(contentsOf: sequence) + for instance in sequence { - try self._sendInsertionIfNecessary(instance) + if let index = self.items.firstIndex(where: { $0.id == instance.id }) { + self.items[index] = instance + try self._sendUpdateIfNecessary(instance) + } else { // insert + self.items.append(instance) + self._index?[instance.stringId] = instance + try self._sendInsertionIfNecessary(instance) + } } + } /// Returns the instance corresponding to the provided [id] @@ -226,7 +234,7 @@ public class StoredCollection: RandomAccessCollection, SomeCollecti /// Schedules a write operation fileprivate func _scheduleWrite() { if self.asynchronousIO { - DispatchQueue(label: "lestorage.queue.write", qos: .utility).sync { // sync to make sure we don't have writes performed at the same time + DispatchQueue(label: "lestorage.queue.write", qos: .utility).asyncAndWait { // sync to make sure we don't have writes performed at the same time self._write() } } else {