Implement full pagination support for task fetching

Refactored the TaskService and TaskViewModel classes to fully support paginated fetching of tasks. The solution fetches tasks page by page until all tasks have been retrieved, accommodating the API's pagination mechanism. Renamed `listAllTasks` to `fetchTasksPage` to better reflect its purpose and introduced a new method, `fetchAllTasks`, to handle the paginated fetching logic.
This commit is contained in:
hunteraraujo
2023-09-27 00:11:24 -07:00
parent 5df70eabd8
commit dc4ca47bc7
2 changed files with 26 additions and 7 deletions

View File

@@ -1,3 +1,4 @@
import 'package:auto_gpt_flutter_client/models/task.dart';
import 'package:auto_gpt_flutter_client/models/task_request_body.dart';
import 'package:auto_gpt_flutter_client/models/task_response.dart';
import 'package:auto_gpt_flutter_client/utils/rest_api_utility.dart';
@@ -22,21 +23,40 @@ class TaskService {
}
}
/// Lists all tasks.
/// Fetches a single page of tasks.
///
/// [currentPage] and [pageSize] are optional pagination parameters.
///
Future<TaskResponse> listAllTasks(
/// [currentPage] and [pageSize] are pagination parameters.
Future<TaskResponse> fetchTasksPage(
{int currentPage = 1, int pageSize = 10}) async {
try {
final response = await api
.get('agent/tasks?current_page=$currentPage&page_size=$pageSize');
return TaskResponse.fromJson(response);
} catch (e) {
throw Exception('Failed to list all tasks: $e');
throw Exception('Failed to fetch a page of tasks: $e');
}
}
/// Fetches all tasks across all pages.
// TODO: Temporaily make page size 10000 until pagination is fixed
Future<List<Task>> fetchAllTasks({int pageSize = 10000}) async {
int currentPage = 1;
List<Task> allTasks = [];
while (true) {
final response =
await fetchTasksPage(currentPage: currentPage, pageSize: pageSize);
allTasks.addAll(response.tasks);
if (response.tasks.length < pageSize) {
// No more tasks to fetch
break;
}
currentPage++;
}
return allTasks;
}
/// Gets details about a specific task.
///
/// [taskId] is the ID of the task.

View File

@@ -52,8 +52,7 @@ class TaskViewModel with ChangeNotifier {
/// Fetches tasks from the data source.
Future<void> fetchTasks() async {
try {
final TaskResponse tasksResponse = await _taskService.listAllTasks();
final tasksFromApi = tasksResponse.tasks;
final tasksFromApi = await _taskService.fetchAllTasks();
_tasks = tasksFromApi
.where((task) => !_taskService.isTaskDeleted(task.id))
.toList();