onRequest method

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

Called when the request is about to be sent.

Implementation

@override
void onRequest(
    RequestOptions options, RequestInterceptorHandler handler) async {
  // 获取缓存模式
  CacheMode cacheMode = _getCacheMode(options);
  if (CacheMode.ONLY_NETWORK == cacheMode ||
      CacheMode.NETWORK_PUT_READ_CACHE == cacheMode) {
    // 如果缓存模式是只走网络和优先走网络则正常发起请求
    return super.onRequest(options, handler);
  }

  if (CacheMode.READ_CACHE_NETWORK_PUT == cacheMode) {
    // 如果缓存模式是优先缓存,则先校验缓存
    var cache = await CacheManager.getInstance().getCacheWithReq(options);
    if (cache == null ||
        cache.expireTime <= DateTime.now().millisecondsSinceEpoch) {
      // 如果没有缓存或者缓存过期了
      return super.onRequest(options, handler);
    }
    return handler.resolve(_buildResponse(cache, options), true);
  }
  return super.onRequest(options, handler);
}