60 lines
1.8 KiB
Dart
60 lines
1.8 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:jiffy/jiffy.dart';
|
|
|
|
import '../api_request.dart';
|
|
import '../errors/network_exception.dart';
|
|
import '../errors/parse_exception.dart';
|
|
import '../errors/server_exception.dart';
|
|
|
|
abstract class MhslApi<T> extends ApiRequest {
|
|
String subpath;
|
|
MhslApi(this.subpath);
|
|
|
|
http.Response? response;
|
|
|
|
Future<http.Response>? request(Uri uri);
|
|
T assemble(String raw);
|
|
|
|
Future<T> run() async {
|
|
final endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
|
|
|
|
final http.Response data;
|
|
try {
|
|
final raw = await request(endpoint);
|
|
if (raw == null) {
|
|
throw const NetworkException(
|
|
userMessage: 'Keine Antwort vom MHSL-Dienst erhalten.',
|
|
technicalDetails: 'mhsl request returned null',
|
|
);
|
|
}
|
|
data = raw;
|
|
} on SocketException catch (e) {
|
|
throw NetworkException(technicalDetails: 'mhsl $subpath: ${e.message}');
|
|
} on TimeoutException catch (e) {
|
|
throw NetworkException.timeout(technicalDetails: 'mhsl $subpath: $e');
|
|
} on http.ClientException catch (e) {
|
|
throw NetworkException(technicalDetails: 'mhsl $subpath: ${e.message}');
|
|
}
|
|
|
|
if (data.statusCode > 299) {
|
|
throw ServerException(
|
|
statusCode: data.statusCode,
|
|
technicalDetails: 'mhsl $subpath HTTP ${data.statusCode}',
|
|
);
|
|
}
|
|
|
|
try {
|
|
return assemble(utf8.decode(data.bodyBytes));
|
|
} catch (e) {
|
|
throw ParseException(technicalDetails: 'mhsl $subpath assemble: $e');
|
|
}
|
|
}
|
|
|
|
static String dateTimeToJson(DateTime time) => Jiffy.parseFromDateTime(time).format(pattern: 'yyyy-MM-dd HH:mm:ss');
|
|
static DateTime dateTimeFromJson(String time) => DateTime.parse(time);
|
|
}
|