Cache Provider

CacheProvider provides the cache abstract class and provides an in-memory cache implementation and a persistent cache implementation for the file system based on this abstract class.

Example

import 'package:cache_provider/cache_provider.dart';
import 'dart:convert';

final class _MockCacheValue extends CacheValue {
  final int _value;
  final DateTime _expiredAt;
  final DateTime _refreshAfter;

  _MockCacheValue(this._value, this._expiredAt, this._refreshAfter);

  @override
  bool isValid() {
    return DateTime.now().isBefore(_expiredAt);
  }

  @override
  bool shouldRefresh() {
    return DateTime.now().isAfter(_refreshAfter);
  }

  static CachePair<_MockCacheValue> _deserialize(String line) {
    final map = jsonDecode(
      line,
      reviver: (key, value) {
        if (key == 'k') {
          return value;
        } else if (key == 'v') {
          return value;
        } else if (key == 'e') {
          return DateTime.parse(value as String);
        } else if (key == 'r') {
          return DateTime.parse(value as String);
        } else if (key == 'c') {
          return DateTime.parse(value as String);
        } else {
          return value;
        }
      },
    );
    return CachePair(
      map['k'],
      _MockCacheValue(map['v'], map['e'], map['r']),
      map['c'],
    );
  }

  static String _serialize(CachePair<_MockCacheValue> pair) {
    return jsonEncode(pair, toEncodable: (object) {
      if (object is CachePair<_MockCacheValue>) {
        return {
          'k': object.key,
          'v': object.data._value,
          'e': object.data._expiredAt.toIso8601String(),
          'r': object.data._refreshAfter.toIso8601String(),
          'c': object.createdAt.toIso8601String(),
        };
      } else {
        throw Exception('unexpected object type: $object');
      }
    });
  }
}

void main() async {
  final inMemoryCache =
      CacheProvider.createInMemoryCache<_MockCacheValue>(Duration(minutes: 1));
  inMemoryCache.get('cache_key', () async {
    await Future.delayed(Duration(seconds: 1));
    return _MockCacheValue(1, DateTime.now().add(Duration(hours: 1)),
        DateTime.now().add(Duration(minutes: 1)));
  });

  final persistentCache =
      await CacheProvider.createPersistentCache<_MockCacheValue>(
    'cache.json',
    Duration(seconds: 30),
    Duration(minutes: 1),
    _MockCacheValue._serialize,
    _MockCacheValue._deserialize,
    (e, s) => print('Error: $e, Stack: $s'),
  );
  await persistentCache.get('cache_key', () async {
    await Future.delayed(Duration(seconds: 1));
    return _MockCacheValue(1, DateTime.now().add(Duration(hours: 1)),
        DateTime.now().add(Duration(minutes: 1)));
  });
}

Libraries

cache_provider
CacheProvider provides the cache abstract class and provides an in-memory cache implementation and a persistent cache implementation for the file system based on this abstract class.