-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcache_manager.dart
81 lines (69 loc) · 2.38 KB
/
cache_manager.dart
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
// Dart imports:
import 'dart:convert';
// Package imports:
import 'package:flutter_cache_manager/flutter_cache_manager.dart' as lib;
// Project imports:
import 'package:notredame/core/services/analytics_service.dart';
import 'package:notredame/core/utils/cache_exception.dart';
import 'package:notredame/locator.dart';
/// Abstraction of the cache management system.
class CacheManager {
static const String tag = "CacheManager";
/// Name of the cache.
static const key = 'ETSMobileCache';
final lib.CacheManager _cacheManager = lib.CacheManager(
lib.Config(key,
stalePeriod: const Duration(days: 30),
maxNrOfCacheObjects: 20,
repo: lib.CacheObjectProvider(databaseName: key)),
);
final AnalyticsService _analyticsService = locator<AnalyticsService>();
/// Get from the cache the value associated with [key].
/// Throw a [CacheException] if the [key] doesn't exist.
Future<String> get(String key) async {
final lib.FileInfo? fileInfo = await _cacheManager.getFileFromCache(key);
if (fileInfo == null) {
_analyticsService.logEvent(
tag, "Trying to access $key from the cache but file doesn't exists");
throw CacheException(
prefix: tag, message: "$key doesn't exist in the cache");
}
return fileInfo.file.readAsString();
}
/// Update/create in the cache the value associated with [key].
Future update(String key, String value) async {
try {
await _cacheManager.putFile(
key, UriData.fromString(value, encoding: utf8).contentAsBytes());
} on Exception catch (e, stacktrace) {
_analyticsService.logError(
tag,
"Exception raised during cache update of $key: ${e.toString()}",
e,
stacktrace);
rethrow;
}
}
/// Delete from the cache the content associated with [key].
Future delete(String key) async {
try {
await _cacheManager.removeFile(key);
} on Exception catch (e, stacktrace) {
_analyticsService.logError(
tag,
"Exception raised during cache delete of $key: ${e.toString()}",
e,
stacktrace);
}
}
/// Empty the cache
Future empty() async {
try {
await _cacheManager.emptyCache();
} on Exception catch (e, stacktrace) {
_analyticsService.logError(
tag, "Exception raised during emptying cache: $e", e, stacktrace);
rethrow;
}
}
}