new start

This commit is contained in:
2025-10-21 21:27:23 +02:00
parent 23ecbe140c
commit 9654072b1d
31 changed files with 540 additions and 2708 deletions
+54
View File
@@ -0,0 +1,54 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiClient {
ApiClient(this.baseUrl, {this.getAccessToken});
final String baseUrl; // z.B. https://api.example.com
final Future<String?> Function()? getAccessToken;
Future<http.Response> _send(String method, String path,
{Object? body}) async {
final uri = Uri.parse('$baseUrl$path');
final headers = {'Content-Type': 'application/json'};
final token = await getAccessToken?.call();
if (token != null) headers['Authorization'] = 'Bearer $token';
switch (method) {
case 'GET':
return http.get(uri, headers: headers);
case 'POST':
return http.post(uri, headers: headers, body: jsonEncode(body));
case 'PUT':
return http.put(uri, headers: headers, body: jsonEncode(body));
case 'DELETE':
return http.delete(uri, headers: headers);
default:
throw UnimplementedError(method);
}
}
Future<Map<String, dynamic>> get(String path) async =>
_decode(await _send('GET', path));
Future<Map<String, dynamic>> post(
String path, Map<String, dynamic> body) async =>
_decode(await _send('POST', path, body: body));
Future<Map<String, dynamic>> put(
String path, Map<String, dynamic> body) async =>
_decode(await _send('PUT', path, body: body));
Future<Map<String, dynamic>> delete(String path) async =>
_decode(await _send('DELETE', path));
Map<String, dynamic> _decode(http.Response r) {
if (r.statusCode >= 200 && r.statusCode < 300) {
if (r.body.isEmpty) return {};
return jsonDecode(r.body) as Map<String, dynamic>;
}
throw ApiException(r.statusCode, r.body);
}
}
class ApiException implements Exception {
final int status;
final String body;
ApiException(this.status, this.body);
@override
String toString() => 'ApiException($status): $body';
}