onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

The callback will be executed before the request is initiated.

If you want to continue the request, call handler.next.

If you want to complete the request with some custom data, you can resolve a Response object with handler.resolve.

If you want to complete the request with an error message, you can reject a DioException object with handler.reject.

Implementation

@override
onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
  if (!CACHE_ENABLE) return handler.next(options);

  // refresh标记是否是刷新缓存
  bool refresh = options.extra["refresh"] == true;

  // 是否磁盘缓存
  bool cacheDisk = options.extra["cacheDisk"] == true;

  // 如果刷新,先删除相关缓存
  if (refresh) {
    // 删除uri相同的内存缓存
    delete(options.uri.toString());

    // 删除磁盘缓存
    if (cacheDisk) {
      await StorageService.to.remove(options.uri.toString());
    }

    return handler.next(options);
  }

  // get 请求,开启缓存
  if (options.extra["noCache"] != true &&
      options.method.toLowerCase() == 'get') {
    String key = options.extra["cacheKey"] ?? options.uri.toString();

    // 策略 1 内存缓存优先,2 然后才是磁盘缓存

    // 1 内存缓存
    var ob = cache[key];
    if (ob != null) {
      //若缓存未过期,则返回缓存内容
      if ((DateTime.now().millisecondsSinceEpoch - ob.timeStamp) / 1000 <
          CACHE_MAXAGE) {
        handler.resolve(ob.response);
      } else {
        //若已过期则删除缓存,继续向服务器请求
        cache.remove(key);
      }
    }

    // 2 磁盘缓存
    if (cacheDisk) {
      var cacheData = StorageService.to.getJson(key);
      if (cacheData != null) {
        handler.resolve(
          Response(
            statusCode: 200,
            data: cacheData,
            requestOptions: options,
          ),
        );
      }
    }
  }
}