dio_cache_interceptor缓存拦截器框架之CachePriority、CacheCipher源码分析(一)

430 阅读2分钟

CachePriority

/// Cache priority.
///
/// Could be useful if you have multiple levels of cache.
/// This allows to separate entries and ease cleanup.
enum CachePriority {
  /// Cache defined as low priority
  low,

  /// Cache defined as normal priority
  normal,

  /// Cache defined as high priority
  high,
}

extension CachePriorityToString on CachePriority {
  String toShortString() {
    return toString().split('.').last;
  }
}

CachePriority 枚举是一个用于定义缓存优先级的枚举类型。它可以在多级缓存场景中使用,用于区分不同级别的缓存条目,并方便进行缓存清理。

枚举成员:

  1. low: 低优先级缓存。
  2. normal: 正常优先级缓存。
  3. high: 高优先级缓存。

toShortString() 扩展方法:

CachePriorityToString 是一个扩展方法,用于将 CachePriority 枚举转换为字符串表示。该方法会将枚举成员的全名转换为短名,例如将 CachePriority.normal 转换为 "normal"

CacheCipher

/// Encrypt content/headers method.
typedef Encrypt = Future<List<int>> Function(List<int> bytes);

/// Decrypt content/headers method.
typedef Decrypt = Future<List<int>> Function(List<int> bytes);

class CacheCipher {
  /// Optional method to decrypt cache content
  final Decrypt decrypt;

  /// Optional method to encrypt cache content
  final Encrypt encrypt;

  const CacheCipher({required this.decrypt, required this.encrypt});

  /// 解密
  static Future<List<int>?> decryptContent(
    CacheOptions options,
    List<int>? bytes,
  ) {
    final checkedCipher = options.cipher;
    if (bytes != null && checkedCipher != null) {
      return checkedCipher.decrypt(bytes);
    }
    return Future.value(bytes);
  }

  /// 加密
  static Future<List<int>?> encryptContent(
    CacheOptions options,
    List<int>? bytes,
  ) {
    final checkedCipher = options.cipher;
    if (bytes != null && checkedCipher != null) {
      return checkedCipher.encrypt(bytes);
    }
    return Future.value(bytes);
  }
}

在这里,CacheCipher 类是一个用于加密和解密缓存内容或头部的辅助类。它接受两个参数 decryptencrypt,这两个参数都是用户自定义的方法,用于实现解密和加密逻辑。

CacheCipher 类包含了两个静态方法 decryptContentencryptContent,用于在进行缓存读取和写入时调用相应的加密和解密方法。

在读取缓存内容时,decryptContent 方法会根据 CacheOptions 中配置的 cipherCacheCipher 实例)来尝试解密数据,如果有加密,则会调用 decrypt 方法进行解密。如果没有加密或解密失败,将返回原始数据。

在写入缓存内容时,encryptContent 方法会根据 CacheOptions 中配置的 cipherCacheCipher 实例)来尝试加密数据,如果有加密,则会调用 encrypt 方法进行加密。如果没有加密或加密失败,将使用原始数据。

这样,通过传递自定义的加密和解密方法给 CacheCipher 类,我们可以在缓存数据时对其进行加密,并在读取数据时进行解密,以保护数据的安全性。