getCacheKeyFromPath static method

String getCacheKeyFromPath(
  1. String? path,
  2. Map<String, dynamic> params,
  3. List<String> ignoreKeys, {
  4. bool hashKey = true,
})

生成缓存键

默认统一使用 SHA-256 哈希生成固定长度缓存键(取前 32 个十六进制字符, 128 bit),避免 token / PII 等参数以明文形式写入本地数据库。

hashKey 仅用于测试或特殊调试场景;生产环境应保持默认 true。

Implementation

static String getCacheKeyFromPath(
  String? path,
  Map<String, dynamic> params,
  List<String> ignoreKeys, {
  bool hashKey = true,
}) {
  if (TextUtil.isEmpty(path)) {
    throw Exception("请求地址不能为空!");
  }

  final buffer = StringBuffer(path!);

  if (params.isNotEmpty) {
    final tempParams = Map<String, dynamic>.from(params);
    tempParams.removeWhere((key, value) => ignoreKeys.contains(key));

    if (tempParams.isNotEmpty) {
      buffer.write('?');
      final sortedKeys = tempParams.keys.toList()..sort();
      for (var i = 0; i < sortedKeys.length; i++) {
        if (i > 0) buffer.write('&');
        final key = sortedKeys[i];
        buffer.write(key);
        buffer.write('=');
        buffer.write(tempParams[key]);
      }
    }
  }

  final rawKey = buffer.toString();

  if (!hashKey) {
    return rawKey;
  }

  final bytes = utf8.encode(rawKey);
  final digest = sha256.convert(bytes);
  return digest.toString().substring(0, 32);
}