cashumit/lib/services/account_cache_service.dart

86 lines
2.8 KiB
Dart

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
class AccountCacheService {
static const String _accountsKey = 'cached_accounts';
static const String _lastUpdatedKey = 'accounts_last_updated';
/// Simpan akun ke cache lokal
static Future<void> saveAccountsLocally(
List<Map<String, dynamic>> accounts) async {
final prefs = await SharedPreferences.getInstance();
// Konversi akun ke JSON string
final accountsJson =
accounts.map((account) => json.encode(account)).toList();
await prefs.setStringList(_accountsKey, accountsJson);
await prefs.setInt(_lastUpdatedKey, DateTime.now().millisecondsSinceEpoch);
}
/// Ambil akun dari cache lokal
static Future<List<Map<String, dynamic>>> getCachedAccounts() async {
final prefs = await SharedPreferences.getInstance();
final accountsJsonList = prefs.getStringList(_accountsKey) ?? [];
if (accountsJsonList.isEmpty) {
return [];
}
return accountsJsonList
.map((jsonString) => json.decode(jsonString) as Map<String, dynamic>)
.toList();
}
/// Periksa apakah cache akun masih valid (kurang dari 1 jam)
static Future<bool> isCacheValid() async {
final prefs = await SharedPreferences.getInstance();
final lastUpdated = prefs.getInt(_lastUpdatedKey) ?? 0;
final now = DateTime.now().millisecondsSinceEpoch;
// Cache valid selama 1 jam (360000 ms)
return (now - lastUpdated) < 360000;
}
/// Hapus cache akun
static Future<void> clearCache() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_accountsKey);
await prefs.remove(_lastUpdatedKey);
}
/// Update cache akun dari server
static Future<void> updateAccountsFromServer(
List<Map<String, dynamic>> accounts) async {
await saveAccountsLocally(accounts);
}
/// Dapatkan akun dengan prioritas: cache valid > data server > fallback kosong
static Future<List<Map<String, dynamic>>> getAccountsWithFallback(
Future<List<Map<String, dynamic>>> Function() serverFetchFunction,
) async {
// Coba ambil dari cache dulu
if (await isCacheValid()) {
final cachedAccounts = await getCachedAccounts();
if (cachedAccounts.isNotEmpty) {
return cachedAccounts;
}
}
// Jika cache tidak valid atau kosong, coba ambil dari server
try {
final serverAccounts = await serverFetchFunction();
if (serverAccounts.isNotEmpty) {
// Simpan ke cache jika berhasil ambil dari server
await updateAccountsFromServer(serverAccounts);
return serverAccounts;
}
} catch (e) {
print('Gagal mengambil akun dari server: $e');
}
// Jika semua gagal, kembalikan cache terakhir (meskipun mungkin expired)
return await getCachedAccounts();
}
}