set method

Future set(
  1. dynamic data, {
  2. bool stream = true,
  3. bool keepData = true,
})

Implementation

Future set(dynamic data, {bool stream = true, bool keepData = true}) async {
  dynamic newData;

  if (data is StorageModel) {
    newData = data.map;
  } else if (data is List<StorageModel>) {
    newData = [for (var item in data) item.map];
  } else {
    newData = data;
  }

  dynamic collectionData;
  if (!keepData) {
    collectionData = newData;
  } else {
    collectionData = await _checkType(newData);
    if (newData is Map) {
      collectionData ??= {};
      for (var key in newData.keys) {
        collectionData[key] = newData[key];
      }
    } else if (newData is List) {
      collectionData ??= [];
      for (var item in newData) {
        if (!collectionData.contains(item)) collectionData.add(item);
      }
    } else {
      collectionData = newData;
    }
  }

  if (stream) {
    for (var streamId in storageListeners.getPathStreamIds(path)) {
      if (storageListeners.hasStreamId(path, streamId)) {
        storageListeners.setDate(path, streamId);
      }
    }
  }

  collectionData = _decodeRefs(collectionData);

  if (parent != null) {
    await parent!.set({collectionId: collectionData});
  } else {
    await storageDatabase.source.setData(collectionId, collectionData);
  }

  _cache = collectionData;
  _cacheLoaded = true;
}