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> execute({ Map? headers, Map? 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> _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; } }