Closed ThinkDigitalSoftware closed 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
.
// 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,
// ...
]);
Thank you so much! This would be a nice addition to the library
@avioli
whats second parameter on this your pasted code which that empty string?
Uri.https('example.org', ''),
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.
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?
@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.
We have an app that pings multiple APIs, but we need caching for just one of them. Can you add whitelisting?