get method

  1. @override
Future get(
  1. String key
)
override

Retrieves a value from the cache by its key.

Returns the cached value associated with the key if it exists and has not expired. If the key does not exist or has expired, returns null.

Throws an exception if the key is null or empty. Implementations should handle deserialization of the stored value if necessary.

  • Parameters:
    • key: A non-null, non-empty string representing the cache key.
  • Returns: The cached value, or null if not found or expired.

Implementation

@override
Future<dynamic> get(String key) async {
  if (key.isEmpty) {
    throw ArgumentError('Cache key cannot be empty');
  }

  try {
    final result = await _executeCommand(['GET', key], isRead: true);

    if (result == null) {
      _stats.misses++;
      _stats.hits--; // Correct the hit count since it's actually a miss
      return null;
    }

    return jsonDecode(result as String);
  } catch (e) {
    _stats.misses++;
    _stats.hits--; // Correct the hit count
    throw CacheException('Failed to retrieve cache item "$key": $e');
  }
}