update method

  1. @override
Future<String?> update(
  1. String key,
  2. String? transform(
    1. String? current
    )
)
override

Reads key, calls transform synchronously, writes its result (null removes), returns it.

Atomic with respect to every other update of key through this store, and, for IndexedDB, through every store over the same database. transform must not await and treats a value it cannot decode as absent. When transform throws, nothing is written and the error is rethrown.

Implementation

@override
Future<String?> update(
  String key,
  String? Function(String? current) transform,
) => _inTransaction('readwrite', (web.IDBTransaction transaction) {
  final web.IDBObjectStore objects = transaction.objectStore(_objectStore);
  final Completer<String?> result = Completer<String?>();
  String? next;
  bool changed = false;
  Object? failure;
  StackTrace? failureTrace;
  final web.IDBRequest get = objects.get(key.toJS);
  get.onsuccess = ((web.Event _) {
    final String? current = _asString(get.result);
    try {
      next = transform(current);
    } on Object catch (error, stackTrace) {
      failure = error;
      failureTrace = stackTrace;
      transaction.abort();
      return;
    }
    final String? value = next;
    if (value == current && (value != null || get.result == null)) {
      return;
    }
    changed = true;
    if (value == null) {
      objects.delete(key.toJS);
    } else {
      objects.put(value.toJS, key.toJS);
    }
  }).toJS;
  transaction.oncomplete = ((web.Event _) {
    result.complete(next);
    if (changed) {
      _announce(key);
    }
  }).toJS;
  transaction.onabort = ((web.Event _) {
    if (result.isCompleted) {
      return;
    }
    final Object? error = failure;
    if (error != null) {
      result.completeError(error, failureTrace);
    } else {
      result.completeError(_storageError('a value could not be written'));
    }
  }).toJS;
  return result.future;
});