put method

  1. @override
Future<void> put(
  1. String key,
  2. T value, {
  3. CacheEntryDelegate<T>? delegate,
})
override

Add / Replace the cache value for the specified key.

  • key: the key
  • value: the value
  • delegate: provides the caller a way of changing the CacheEntry before persistence

Implementation

@override
Future<void> put(String key, T value, {CacheEntryDelegate<T>? delegate}) {
  // Current time
  final now = clock.now();
  // #region Statistics
  Stopwatch? watch;
  Future<void> Function(bool) posPut = (_) => Future<void>.value();
  if (statsEnabled) {
    watch = clock.stopwatch()..start();
    posPut = (bool ok) {
      if (ok) {
        stats.increasePuts();
      }
      if (watch != null) {
        stats.addPutTime(watch.elapsedMicroseconds);
        watch.stop();
      }

      return Future<void>.value();
    };
  }
  // #endregion

  // Try to get the entry from the cache
  return _getStorageInfo(key).then((info) {
    final expired = info != null && info.isExpired(now);
    // If the entry does not exist or is expired
    if (info == null || expired) {
      // If expired we remove it
      final prePut = expired
          ? _removeStorageEntry(key, CacheEntryExpiredEvent<T>(this, info))
          : Future<void>.value();

      // And finally we add it to the cache
      return prePut
          .then((_) =>
              _newEntry(_entryBuilder(key, value, now, delegate: delegate)))
          .then(posPut);
    } else {
      // Already present let's update the cache instead
      return _replaceEntry(info, value, now).then((_) => posPut(true));
    }
  });
}