You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.7 KiB
Dart
58 lines
1.7 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:test_sa/core/enums.dart';
|
|
|
|
class ApiClient {
|
|
final String baseUrl, endPoint;
|
|
final RequestMethod requestMethod;
|
|
|
|
ApiClient.request({
|
|
required this.baseUrl,
|
|
required this.endPoint,
|
|
required this.requestMethod,
|
|
});
|
|
|
|
Future<Map<String, dynamic>> execute({
|
|
Map<String, String>? headers,
|
|
Map<String, dynamic>? queryParameters,
|
|
Object? body,
|
|
}) async {
|
|
final url = Uri.tryParse(baseUrl + endPoint);
|
|
if (url != null) {
|
|
late http.Response response;
|
|
switch (requestMethod) {
|
|
case RequestMethod.get:
|
|
response = await http.get(url, headers: headers);
|
|
break;
|
|
case RequestMethod.post:
|
|
response = await http.post(url, headers: headers, body: body);
|
|
break;
|
|
case RequestMethod.put:
|
|
response = await http.put(url, headers: headers, body: body);
|
|
break;
|
|
case RequestMethod.delete:
|
|
response = await http.delete(url, headers: headers, body: body);
|
|
break;
|
|
}
|
|
return await _handleResponse(response);
|
|
} else {
|
|
throw ApiExceptionsEnum.other;
|
|
}
|
|
}
|
|
|
|
Future<Map<String, dynamic>> _handleResponse(http.Response response) {
|
|
print('status code ${response.statusCode} : ${response.request?.url}');
|
|
if (response.statusCode == 200) {
|
|
return jsonDecode(response.body);
|
|
} else if (response.statusCode == 401) {
|
|
throw ApiExceptionsEnum.unauthorized;
|
|
} else if (response.statusCode == 400) {
|
|
throw ApiExceptionsEnum.badRequest;
|
|
} else if (response.statusCode == 500) {
|
|
throw ApiExceptionsEnum.internalServerError;
|
|
}
|
|
throw ApiExceptionsEnum.unknown;
|
|
}
|
|
}
|