-
-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathsuggestion_cache.dart
More file actions
47 lines (39 loc) · 1.44 KB
/
suggestion_cache.dart
File metadata and controls
47 lines (39 loc) · 1.44 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
import 'package:smooth_app/database/dao_autocomplete.dart';
import 'package:smooth_app/database/local_database.dart';
import 'package:smooth_app/pages/input/server_suggestion.dart';
class SuggestionCache {
SuggestionCache({
required this.serverSuggestion,
required this.localDatabase,
});
final ServerSuggestion serverSuggestion;
final LocalDatabase localDatabase;
// namespace string → namespace DB id (avoids repeated DB lookup per session)
final Map<String, int> _namespaceIdCache = <String, int>{};
Future<int> _getNamespaceId(final String namespace) async {
final int? cached = _namespaceIdCache[namespace];
if (cached != null) {
return cached;
}
final int id = await DaoNamespace(localDatabase).getOrCreateId(namespace);
_namespaceIdCache[namespace] = id;
return id;
}
Future<List<String>> getSuggestions(final String soFar) async {
final String namespace = serverSuggestion.getNamespace(soFar);
final int namespaceId = await _getNamespaceId(namespace);
final DaoAutocompleteCache daoCache = DaoAutocompleteCache(localDatabase);
// 1. DB
final List<String>? db = await daoCache.get(namespaceId, soFar);
if (db != null) {
return db;
}
// 2. Server
final List<String> results = await serverSuggestion
.getSuggestionsFromServer(soFar);
if (results.isNotEmpty) {
await daoCache.put(namespaceId, soFar, results);
}
return results;
}
}