Migrate sync queue persistence to store adapters
This commit is contained in:
@@ -1,27 +1,43 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:relationship_saver/core/config/app_config.dart';
|
||||
import 'package:relationship_saver/features/sync/storage/sync_state_store.dart';
|
||||
import 'package:relationship_saver/features/sync/storage/sync_state_store_hive.dart';
|
||||
import 'package:relationship_saver/features/sync/storage/sync_state_store_provider.dart';
|
||||
import 'package:relationship_saver/features/sync/storage/sync_state_store_shared_prefs.dart';
|
||||
import 'package:relationship_saver/features/sync/sync_state.dart';
|
||||
import 'package:relationship_saver/integrations/backend/models/backend_models.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Persists queued local mutations and sync cursor metadata.
|
||||
class SyncQueueRepository extends AsyncNotifier<SyncState> {
|
||||
static const String _storageKey = 'sync_queue_state_v1';
|
||||
|
||||
@override
|
||||
Future<SyncState> build() async {
|
||||
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
final String? raw = prefs.getString(_storageKey);
|
||||
if (raw == null || raw.isEmpty) {
|
||||
final SyncStateStore store = ref.read(syncStateStoreProvider);
|
||||
SyncStateRecord? record = await store.read();
|
||||
|
||||
if ((record == null || record.rawState.isEmpty) &&
|
||||
AppConfig.useHiveLocalDb &&
|
||||
store is HiveSyncStateStore) {
|
||||
final SharedPrefsSyncStateStore legacyStore = SharedPrefsSyncStateStore();
|
||||
final SyncStateRecord? legacy = await legacyStore.read();
|
||||
if (legacy != null && legacy.rawState.isNotEmpty) {
|
||||
await store.write(rawState: legacy.rawState);
|
||||
await legacyStore.clear();
|
||||
record = await store.read();
|
||||
}
|
||||
}
|
||||
|
||||
if (record == null || record.rawState.isEmpty) {
|
||||
return SyncState.empty;
|
||||
}
|
||||
|
||||
try {
|
||||
final Map<String, dynamic> json = jsonDecode(raw) as Map<String, dynamic>;
|
||||
final Map<String, dynamic> json =
|
||||
jsonDecode(record.rawState) as Map<String, dynamic>;
|
||||
return SyncState.fromJson(json);
|
||||
} on FormatException {
|
||||
await prefs.remove(_storageKey);
|
||||
await store.clear();
|
||||
return SyncState.empty;
|
||||
}
|
||||
}
|
||||
@@ -121,8 +137,9 @@ class SyncQueueRepository extends AsyncNotifier<SyncState> {
|
||||
|
||||
Future<void> _setState(SyncState next) async {
|
||||
state = AsyncData<SyncState>(next);
|
||||
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_storageKey, jsonEncode(next.toJson()));
|
||||
await ref
|
||||
.read(syncStateStoreProvider)
|
||||
.write(rawState: jsonEncode(next.toJson()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user