-
Notifications
You must be signed in to change notification settings - Fork 75
Handling cache with client only
llfbandit edited this page Mar 27, 2023
·
5 revisions
The package won't handle any specific rule, so you will most likely have to make your own. Here's a few samples to achieve correct behaviour with client only.
The samples below assume to add an interceptor before DioCacheInterceptor
to control your own rules.
Return cache if the response is aged less than 5 minutes.
dioInstance..interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, handler) {
final key = cacheOptions.defaultCacheKeyBuilder(request);
final cache = await store.get(key);
if (cache != null && DateTime.now().difference(cache.responseDate).inMinutes < 5) {
return handler.resolve(cache.toResponse(options, fromNetwork: false));
}
return handler.next(options);
},
));
Store specific URLs only.
dioInstance..interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, handler) {
if (options.uri.toString().contains('<uri_to_cache_here>')) {
final cacheOptions = CacheOptions.fromExtra(options)!;
options.extra = cacheOptions.copyWith(policy: CachePolicy.forceCache).toExtra();
return handler.next(options);
}
return handler.next(options);
},
));
// Global options
final options = const CacheOptions(
store: MemCacheStore(),
policy: CachePolicy.forceCache,
maxStale: const Duration(days: 1),
);
// ...
// Each time, this request will postpone maxStale from current date time + maxStale
// from global options
final response = await dio.get('https://www.foo.com');
// ...
// This request will not modify maxStale
// Response will stale after 1 day and origin server will be called
final response = await dio.get('https://www.foo.com',
options: options.copyWith(maxStale: Nullable(null)).toOptions(),
);