update
This commit is contained in:
No files matched your search
@@ -0,0 +1,59 @@
|
||||
part of '../app/app.dart';
|
||||
|
||||
class ApiClient {
|
||||
ApiClient({required this.baseUrl, this.token});
|
||||
|
||||
final String baseUrl;
|
||||
final String? token;
|
||||
|
||||
Uri _uri(String path, [Map<String, String>? query]) {
|
||||
final normalizedBase = normalizeBaseUrl(baseUrl);
|
||||
final base = Uri.parse(normalizedBase);
|
||||
return base.replace(
|
||||
path: '${base.path.replaceAll(RegExp(r'/$'), '')}/$path',
|
||||
queryParameters: query,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, String> get _headers => {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
if (token != null) 'Authorization': 'Bearer $token',
|
||||
};
|
||||
|
||||
Future<Map<String, dynamic>> post(
|
||||
String path,
|
||||
Map<String, dynamic> body,
|
||||
) async {
|
||||
final response = await http.post(
|
||||
_uri(path),
|
||||
headers: _headers,
|
||||
body: jsonEncode(body),
|
||||
);
|
||||
return _decode(response);
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> get(
|
||||
String path, [
|
||||
Map<String, String>? query,
|
||||
]) async {
|
||||
final response = await http.get(_uri(path, query), headers: _headers);
|
||||
return _decode(response);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decode(http.Response response) {
|
||||
final decoded = response.body.isEmpty
|
||||
? <String, dynamic>{}
|
||||
: jsonDecode(response.body);
|
||||
if (response.statusCode >= 200 && response.statusCode < 300) {
|
||||
return decoded is Map<String, dynamic> ? decoded : {'data': decoded};
|
||||
}
|
||||
final message = decoded is Map ? decoded['message'] : null;
|
||||
throw ApiException(message?.toString() ?? 'Koneksi ke server gagal.');
|
||||
}
|
||||
}
|
||||
|
||||
class ApiException implements Exception {
|
||||
ApiException(this.message);
|
||||
final String message;
|
||||
}
|
||||
Reference in New Issue
Block a user