Files
Client/lib/api/requestCache.dart
T
2026-05-04 13:54:39 +02:00

50 lines
1.3 KiB
Dart

import 'dart:convert';
import 'package:localstore/localstore.dart';
import 'apiResponse.dart';
abstract class RequestCache<T extends ApiResponse?> {
static const int cacheNothing = 0;
static const int cacheMinute = 60;
static const int cacheHour = 60 * 60;
static const int cacheDay = 60 * 60 * 24;
static String collection = 'MarianumMobile';
int maxCacheTime;
void Function(T)? onUpdate;
void Function(Exception) onError;
bool? renew;
RequestCache(this.maxCacheTime, this.onUpdate, {this.onError = ignore, this.renew = false});
static void ignore(Exception e) {}
Future<void> start(String document) async {
final tableData = await Localstore.instance.collection(collection).doc(document).get();
if (tableData != null) {
onUpdate?.call(onLocalData(tableData['json']));
}
if (DateTime.now().millisecondsSinceEpoch - (maxCacheTime * 1000) < (tableData?['lastupdate'] ?? 0)) {
if (renew == null || !renew!) return;
}
try {
final newValue = await onLoad();
onUpdate?.call(newValue);
Localstore.instance.collection(collection).doc(document).set({
'json': jsonEncode(newValue),
'lastupdate': DateTime.now().millisecondsSinceEpoch,
});
} on Exception catch (e) {
onError(e);
}
}
T onLocalData(String json);
Future<T> onLoad();
}