put<T> method

Future<void> put<T>(
  1. String key,
  2. T data, {
  3. CacheOptions options = const CacheOptions(),
})

Puts a cache entry

Implementation

Future<void> put<T>(
  String key,
  T data, {
  CacheOptions options = const CacheOptions(),
}) async {
  await _ensureInitialized();

  try {
    // Calculate the size of the data
    final size = _calculateDataSize(data);

    // Create the metadata
    final metadata = CacheEntryMetadata(
      key: key,
      createdAt: DateTime.now(),
      lastAccessedAt: DateTime.now(),
      expiresAt:
          options.maxAgeSeconds != null
              ? DateTime.now().add(Duration(seconds: options.maxAgeSeconds!))
              : null,
      size: size,
      contentType: T.toString(),
      additionalMetadata: options.additionalMetadata,
    );

    // Store the entry in each level
    for (final level in options.levels) {
      await _storeInLevel(
        key,
        data,
        metadata,
        level,
        compress: options.compress,
      );
    }

    logger?.info('Cached entry $key (${_formatSize(size)})');
  } catch (e) {
    logger?.error('Error caching entry $key: $e');
    rethrow;
  }
}