Client/lib/api/requestCache.dart
Elias Müller 97b414412d Revert "Updated feedback to include screenshot and drawings"
This reverts commit 7b3c0b488541c20a76148b91439f5ded6c868777.
2024-03-17 22:49:59 +01:00

49 lines
1.3 KiB
Dart

import 'dart:convert';
import 'package:localstore/localstore.dart';
import 'package:marianum_mobile/api/apiResponse.dart';
import 'webuntis/webuntisError.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;
int maxCacheTime;
Function(T) onUpdate;
Function(Exception) onError;
bool? renew;
RequestCache(this.maxCacheTime, this.onUpdate, {this.onError = ignore, this.renew = false});
static void ignore(Exception e) {}
void start(String file, String document) async {
Map<String, dynamic>? tableData = await Localstore.instance.collection(file).doc(document).get();
if(tableData != null) {
onUpdate(onLocalData(tableData['json']));
}
if(DateTime.now().millisecondsSinceEpoch - (maxCacheTime * 1000) < (tableData?['lastupdate'] ?? 0)) {
if(renew == null || !renew!) return;
}
try {
T newValue = await onLoad();
onUpdate(newValue);
Localstore.instance.collection(file).doc(document).set({
"json": jsonEncode(newValue),
"lastupdate": DateTime.now().millisecondsSinceEpoch
});
} on WebuntisError catch(e) {
onError(e);
}
}
T onLocalData(String json);
Future<T> onLoad();
}