add method

  1. @override
Future<bool> add(
  1. String key,
  2. dynamic value,
  3. Duration ttl
)
override

Stores a value in the cache if the key does not exist.

Returns true if the item was actually added, false otherwise.

  • Parameters:
    • key: A non-null, non-empty string representing the cache key.
    • value: The data to be cached.
    • ttl: The duration for which the item should remain in the cache.

Implementation

@override
Future<bool> add(String key, dynamic value, Duration ttl) async {
  if (key.isEmpty) throw ArgumentError('Cache key cannot be empty');

  final serializedValue = jsonEncode(value);
  final ttlInSeconds = ttl.inSeconds;

  // SET key value NX EX ttl
  final result = await _executeCommand([
    'SET',
    key,
    serializedValue,
    'NX',
    'EX',
    ttlInSeconds > 0 ? ttlInSeconds : 1,
  ]);

  if (result == 'OK') {
    _stats.sets++;
    return true;
  }

  return false;
}