97 lines
2.6 KiB
Dart
97 lines
2.6 KiB
Dart
import "dart:convert";
|
|
import "dart:typed_data";
|
|
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>> postMultipart(
|
|
String path, {
|
|
required String fieldName,
|
|
required Uint8List bytes,
|
|
required String filename,
|
|
Map<String, String>? fields,
|
|
}) async {
|
|
final request = http.MultipartRequest("POST", _uri(path));
|
|
if (fields != null) {
|
|
request.fields.addAll(fields);
|
|
}
|
|
request.files.add(
|
|
http.MultipartFile.fromBytes(
|
|
fieldName,
|
|
bytes,
|
|
filename: filename,
|
|
),
|
|
);
|
|
final streamed = await _client.send(request);
|
|
final response = await http.Response.fromStream(streamed);
|
|
_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}");
|
|
}
|
|
}
|
|
}
|