Skip to content

Commit e607dbf

Browse files
committed
feat(shared): add configurable delay to ThrottledFetchingService
Enhances the `ThrottledFetchingService` to be a better API citizen by introducing a configurable delay between sequential page fetches. - Adds a `delayBetweenRequests` parameter to the `fetchAll` method with a default of 200ms. - Implements `Future.delayed` within the pagination loop to throttle requests. - Removes the unused `batchSize` parameter to clean up the method signature. This prevents overwhelming the server with rapid-fire requests when fetching a large number of pages.
1 parent f33e7ae commit e607dbf

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

lib/shared/services/throttled_fetching_service.dart

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// ignore_for_file: inference_failure_on_instance_creation
2+
13
import 'dart:async';
24

35
import 'package:core/core.dart';
@@ -22,16 +24,17 @@ class ThrottledFetchingService {
2224
/// Fetches all items of type [T] from the provided [repository].
2325
///
2426
/// It fetches pages in parallel batches to optimize loading time without
25-
/// overwhelming the server.
27+
/// overwhelming the server. It includes a configurable delay between
28+
/// requests to act as a good API citizen.
2629
///
2730
/// - [repository]: The data repository to fetch from.
2831
/// - [sort]: The sorting options for the query.
29-
/// - [batchSize]: The number of pages to fetch in each concurrent batch.
30-
/// Defaults to 5.
32+
/// - [delayBetweenRequests]: The duration to wait between fetching pages.
33+
/// Defaults to 200 milliseconds.
3134
Future<List<T>> fetchAll<T>({
3235
required DataRepository<T> repository,
3336
required List<SortOption> sort,
34-
int batchSize = 5,
37+
Duration delayBetweenRequests = const Duration(milliseconds: 200),
3538
}) async {
3639
final allItems = <T>[];
3740
String? cursor;
@@ -51,6 +54,9 @@ class ThrottledFetchingService {
5154
// misbehaving API by also checking if the cursor is null, which would
5255
// otherwise cause an infinite loop by re-fetching the first page.
5356
while (hasMore && cursor != null) {
57+
// Introduce a delay to avoid overwhelming the server.
58+
await Future.delayed(delayBetweenRequests);
59+
5460
final response = await repository.readAll(
5561
sort: sort,
5662
pagination: PaginationOptions(cursor: cursor),

0 commit comments

Comments
 (0)