add method
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,
],
isWrite: true,
);
return result == 'OK';
}