Initial commit
This commit is contained in:
71
flutter_app/lib/services/api_client.dart
Normal file
71
flutter_app/lib/services/api_client.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
import "dart:convert";
|
||||
import "package:http/http.dart" as http;
|
||||
import "../config/api_config.dart";
|
||||
|
||||
class ApiClient {
|
||||
final http.Client _client;
|
||||
|
||||
ApiClient({http.Client? client}) : _client = client ?? http.Client();
|
||||
|
||||
Uri _uri(String path, [Map<String, dynamic>? query]) {
|
||||
return Uri.parse(ApiConfig.baseUrl).replace(
|
||||
path: path,
|
||||
queryParameters: query?.map((key, value) => MapEntry(key, "$value")),
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<dynamic>> getList(
|
||||
String path, {
|
||||
Map<String, dynamic>? query,
|
||||
}) async {
|
||||
final response = await _client.get(_uri(path, query));
|
||||
_ensureSuccess(response);
|
||||
return jsonDecode(response.body) as List<dynamic>;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> getMap(
|
||||
String path, {
|
||||
Map<String, dynamic>? query,
|
||||
}) async {
|
||||
final response = await _client.get(_uri(path, query));
|
||||
_ensureSuccess(response);
|
||||
return jsonDecode(response.body) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> post(
|
||||
String path,
|
||||
Map<String, dynamic> body,
|
||||
) async {
|
||||
final response = await _client.post(
|
||||
_uri(path),
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: jsonEncode(body),
|
||||
);
|
||||
_ensureSuccess(response);
|
||||
return jsonDecode(response.body) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> put(
|
||||
String path,
|
||||
Map<String, dynamic> body,
|
||||
) async {
|
||||
final response = await _client.put(
|
||||
_uri(path),
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: jsonEncode(body),
|
||||
);
|
||||
_ensureSuccess(response);
|
||||
return jsonDecode(response.body) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<void> delete(String path) async {
|
||||
final response = await _client.delete(_uri(path));
|
||||
_ensureSuccess(response);
|
||||
}
|
||||
|
||||
void _ensureSuccess(http.Response response) {
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw Exception("Request failed: ${response.statusCode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user