anyway/frontend/lib/utils/fetch_trip.dart
Remy Moll c87a01b2e8
All checks were successful
Build and push docker image / Build (pull_request) Successful in 1m54s
Build and release APK / Build APK (pull_request) Successful in 5m32s
overhaul using a trip struct that notifies its ui dependencies
2024-08-03 17:17:48 +02:00

87 lines
2.1 KiB
Dart

import "dart:convert";
import "dart:developer";
import 'package:dio/dio.dart';
import 'package:anyway/constants.dart';
import "package:anyway/structs/landmark.dart";
import "package:anyway/structs/trip.dart";
import "package:anyway/structs/preferences.dart";
Dio dio = Dio(
BaseOptions(
baseUrl: API_URL_BASE,
// baseUrl: 'http://localhost:8000',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 120),
// api is notoriously slow
// headers: {
// HttpHeaders.userAgentHeader: 'dio',
// 'api': '1.0.0',
// },
contentType: Headers.jsonContentType,
responseType: ResponseType.json,
),
);
fetchTrip(
Trip trip,
Future<UserPreferences> preferences,
) async {
UserPreferences prefs = await preferences;
Map<String, dynamic> data = {
"preferences": prefs.toJson(),
"start": trip.landmarks!.first.location,
};
String dataString = jsonEncode(data);
log(dataString);
final response = await dio.post(
"/trip/new",
data: data
);
// handle errors
if (response.statusCode != 200) {
trip.updateUUID("error");
throw Exception('Failed to load trip');
}
if (response.data["error"] != null) {
trip.updateUUID("error");
throw Exception(response.data["error"]);
}
log(response.data.toString());
Map<String, dynamic> json = response.data;
// only fill in the trip "meta" data for now
trip.loadFromJson(json);
String? nextUUID = json["first_landmark_uuid"];
while (nextUUID != null) {
var (landmark, newUUID) = await fetchLandmark(nextUUID);
trip.addLandmark(landmark);
nextUUID = newUUID;
}
}
Future<(Landmark, String?)> fetchLandmark(String uuid) async {
final response = await dio.get(
"/landmark/$uuid"
);
// handle errors
if (response.statusCode != 200) {
throw Exception('Failed to load landmark');
}
if (response.data["error"] != null) {
throw Exception(response.data["error"]);
}
log(response.data.toString());
Map<String, dynamic> json = response.data;
String? nextUUID = json["next_uuid"];
return (Landmark.fromJson(json), nextUUID);
}