hurshi / dio-http-cache

http cache lib for Flutter dio like RxCache
Apache License 2.0
274 stars 223 forks source link

Option to whitelist urls for caching #43

Closed ThinkDigitalSoftware closed 4 years ago

ThinkDigitalSoftware commented 4 years ago

We have an app that pings multiple APIs, but we need caching for just one of them. Can you add whitelisting?

avioli commented 4 years ago

You can solve this by adding a custom Dio interceptor before the cache to remove your cache options if the request is for a non-whitelisted url.

Actually you only need to set options.extra[DIO_CACHE_KEY_TRY_CACHE] = false.

avioli commented 4 years ago
// dio_cache_whitelist_interceptor.dart
import 'package:dio_http_cache/dio_http_cache.dart' show DIO_CACHE_KEY_TRY_CACHE;
import 'package:dio/dio.dart';

class DioCacheWhitelist extends Interceptor {
  DioCacheWhitelist(this.whitelist);

  final List<Uri> whitelist;

  @override
  Future onRequest(RequestOptions options) async {
    final target = options.uri;
    if (!whitelist
        .any((uri) => uri.scheme == target.scheme && uri.host == target.host)) {
      print('NOT whitelisted for caching: $target');
      options.extra[DIO_CACHE_KEY_TRY_CACHE] = false;
    }
    return options;
  }
}

Use like:


Dio()..interceptors.addAll([
  // ...
  DioCacheWhitelist([
    Uri.https('example.org', ''),
  ]),
  DioCacheManager(CacheConfig()).interceptor,
  // ...
]);
ThinkDigitalSoftware commented 4 years ago

Thank you so much! This would be a nice addition to the library

pishguy commented 3 years ago

@avioli

whats second parameter on this your pasted code which that empty string?

Uri.https('example.org', ''),
avioli commented 3 years ago

If you are using an IDE (like Android Studio) or an editor that has something like IntelliSense (VSCode) you could right-click on the https keyword and view the definition.

Here’s the Dart page to the Uri class: https://api.dart.dev/stable/2.9.3/dart-core/Uri-class.html

I hope that helps.

pishguy commented 3 years ago

If you are using an IDE (like Android Studio) or an editor that has something like IntelliSense (VSCode) you could right-click on the https keyword and view the definition.

Here’s the Dart page to the Uri class: https://api.dart.dev/stable/2.9.3/dart-core/Uri-class.html

I hope that helps.

yes i see, url's should be define completely when we want to cache?

avioli commented 3 years ago

@MahdiPishguy the code snippet I posted above is public domain - feel free to change it to your liking.

It expects Uris, which are immutable by design.

You can do whatever you want with the code - you can match with a String or a Pattern, or a custom class you specify.

It is only limited by our imagination.