-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache_interceptor.dart
More file actions
89 lines (76 loc) · 2.69 KB
/
Copy pathcache_interceptor.dart
File metadata and controls
89 lines (76 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import 'package:dio/dio.dart';
import 'package:dio_cache_interceptor/dio_cache_interceptor.dart';
import 'package:fetch_tray_cache_plugin/src/fetch_tray_cache_base.dart';
import 'package:logger/logger.dart';
/// Custom interceptor to handle cache expiration. This is necessary because
/// [dio_cache_interceptor] does not support cache expiration on the client side.
/// So if the server does not return a `Cache-Control` header, the cache will
/// never expire.
///
/// This interceptor checks if the cache is older than [maxAge] and deletes
/// it if it is. If the cache is not older than [maxAge], it returns the cached
/// response. If there is no cache, it continues the request.
///
/// [cacheOptions] have to be passed in order to figure out the cache key and
/// actually retrieve the cached item.
///
/// This interceptor should be used before [DioCacheInterceptor] to avoid
/// unnecessary requests.
class TrayCacheInterceptor extends Interceptor {
final Duration maxAge;
final CacheOptions cacheOptions;
final Level logLevel;
get logger => Logger(
printer: PrettyPrinter(
methodCount: 0,
printTime: true,
),
level: logLevel);
TrayCacheInterceptor({
required this.cacheOptions,
required this.maxAge,
this.logLevel = Level.error,
});
@override
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
// TODO: implement filter for logger
/* final requestShouldLog =
options.extra[TrayCachePluginKeys.requestShouldLog] as bool? ?? false; */
final logPrefix =
'[fetch_tray_cache_plugin] ${options.method} ${options.uri}';
final key = cacheOptions.keyBuilder(options);
final store = cacheOptions.store;
final requestCacheDuration =
options.extra[TrayCachePluginKeys.requestCacheDuration] as Duration?;
final ignoreCache =
CacheOptions.fromExtra(options)?.policy == CachePolicy.noCache;
if (store != null && !ignoreCache) {
final cache = await store.get(key);
if (cache != null) {
final difference = DateTime.now().difference(cache.responseDate);
final cacheDuration = requestCacheDuration ?? maxAge;
if (difference <= cacheDuration) {
logger.i(
'$logPrefix Cache hit, returning cached response',
);
return handler.resolve(
cache.toResponse(
options,
fromNetwork: false,
),
);
} else {
logger.i(
'$logPrefix Cache too old, deleting...',
);
await store.delete(key);
}
}
}
logger.i(
'$logPrefix Sending request over network',
);
handler.next(options);
}
}