putCacheWithResp method

Future<void> putCacheWithResp(
  1. Response response,
  2. int defaultCacheTime
)

根据返回结果保存缓存

Implementation

Future<void> putCacheWithResp(Response response, int defaultCacheTime) async {
  try {
    var cacheKey = getCacheKeyWithReq(response.requestOptions);
    if (cacheKey != null) {
      // 获取response bytes 数据
      List<int>? data;
      if (response.requestOptions.responseType == ResponseType.bytes) {
        data = response.data;
      } else {
        data = utf8.encode(jsonEncode(response.data));
      }

      if (data != null) {
        // bytes转String并保存
        Uint8List bytes = Uint8List.fromList(data);
        String cacheValue = utf8.decode(bytes);

        Map<String, dynamic> result = jsonDecode(cacheValue);

        var extra = response.requestOptions.extra;
        String filedCode = extra[RespConfig.option_filed_code] ?? "";
        String successCode =
            extra[RespConfig.option_filed_success_code] ?? "";

        dynamic cd = result[filedCode];
        String code = cd?.toString() ?? "-1";

        if (code == successCode) {
          int cacheTime = extra[CacheStrategy.CACHE_TIME] ?? defaultCacheTime;
          int expireTime = DateTime.now().millisecondsSinceEpoch + cacheTime;
          var cache = HttpCacheObj(cacheKey, cacheValue, expireTime);

          if (isAppCache()) {
            // 先删除老的缓存
            await _database?.delete(
              "HttpCacheObj",
              where: "cacheKey = ?",
              whereArgs: [cacheKey],
            );

            await _database?.insert("HttpCacheObj", cache.toJson());
          } else {
            _otherAppCache[cacheKey] = cache;
          }
        }
      }
    }
  } catch (e) {
    Log.w("Http request cache error!", error: e);
  }
}