Pagination in chat message sync

This commit is contained in:
2025-11-23 12:18:46 +08:00
parent b151ef6686
commit 5ee61dbef2

View File

@@ -343,19 +343,48 @@ class MessagesNotifier extends _$MessagesNotifier {
return; return;
} }
final resp = await _apiClient.post( // Sync with pagination support using timestamp-based cursor
'/sphere/chat/${_room.id}/sync', int? totalMessages;
data: { int syncedCount = 0;
'last_sync_timestamp': int lastSyncTimestamp =
lastMessage.toRemoteMessage().updatedAt.millisecondsSinceEpoch, lastMessage.toRemoteMessage().updatedAt.millisecondsSinceEpoch;
},
);
final response = MessageSyncResponse.fromJson(resp.data); do {
talker.log('Sync response: ${response.messages.length} changes'); final resp = await _apiClient.post(
for (final message in response.messages) { '/sphere/chat/${_room.id}/sync',
await receiveMessage(message); data: {'last_sync_timestamp': lastSyncTimestamp},
} );
// Read total count from header on first request
if (totalMessages == null) {
totalMessages = int.parse(
resp.headers['x-total']?.firstOrNull ?? '0',
);
talker.log('Total messages to sync: $totalMessages');
}
final response = MessageSyncResponse.fromJson(resp.data);
final messagesCount = response.messages.length;
talker.log(
'Sync page: synced=$syncedCount/$totalMessages, count=$messagesCount',
);
for (final message in response.messages) {
await receiveMessage(message);
}
syncedCount += messagesCount;
// Update cursor to the last message's createdAt for next page
if (response.messages.isNotEmpty) {
lastSyncTimestamp =
response.messages.last.createdAt.millisecondsSinceEpoch;
}
// Continue if there are more messages to fetch
} while (syncedCount < totalMessages);
talker.log('Sync complete: synced $syncedCount messages');
} catch (err, stackTrace) { } catch (err, stackTrace) {
talker.log( talker.log(
'Error syncing messages', 'Error syncing messages',