Client/lib/api/requestCache.dart

32 lines
841 B
Dart

import 'dart:convert';
import 'package:localstore/localstore.dart';
abstract class RequestCache<T> {
int maxCacheTime;
Function(T) onUpdate;
RequestCache(this.maxCacheTime, this.onUpdate);
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)) {
return;
}
T newValue = await onLoad();
onUpdate(newValue);
Localstore.instance.collection(file).doc(document).set({
"json": jsonEncode(newValue),
"lastupdate": DateTime.now().millisecondsSinceEpoch
});
}
T onLocalData(String json);
Future<T> onLoad();
}