Skip to content

Instantly share code, notes, and snippets.

@KingsleyUsoroeno
Created February 8, 2022 06:13
Show Gist options
  • Save KingsleyUsoroeno/5a6072b2a24233d8e40121038ab82cf6 to your computer and use it in GitHub Desktop.
Save KingsleyUsoroeno/5a6072b2a24233d8e40121038ab82cf6 to your computer and use it in GitHub Desktop.
class ApiBaseHelper {
final String baseUrl;
final PreferenceManager preferenceManager;
ApiBaseHelper({
required this.baseUrl,
required this.preferenceManager,
});
Future<Dio> _getInstance() async {
final String? token = await preferenceManager.readString(userToken);
Map<String, dynamic> headers = {};
headers['Content-Type'] = 'application/json';
headers['Accept'] = 'application/json';
if (token != null) headers['Authorization'] = 'Bearer $token';
return Dio(BaseOptions(
baseUrl: baseUrl,
responseType: ResponseType.json,
connectTimeout: 30000,
receiveTimeout: 30000,
))
..options.headers = headers
..interceptors.addAll([
LoggingInterceptor.loggingInterceptor(),
]);
}
Future<Response> get(String url) async {
try {
final client = await _getInstance();
return await client.get(url);
} on DioError catch (e) {
throw _getDioNetworkException(e);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> post(String url, {dynamic data}) async {
try {
final client = await _getInstance();
return await client.post(url, data: data);
} on DioError catch (e) {
throw _getDioNetworkException(e);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> put(String url, dynamic data) async {
try {
final client = await _getInstance();
return await client.put(url, data: data);
} on DioError catch (e) {
throw _getDioNetworkException(e);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> patch(String url, dynamic data) async {
try {
final client = await _getInstance();
return await client.patch(url, data: data);
} on DioError catch (e) {
throw _getDioNetworkException(e);
} catch (e) {
throw Exception(e.toString());
}
}
Future<Response> delete(String url) async {
try {
final client = await _getInstance();
return await client.delete(url);
} on DioError catch (e) {
throw _getDioNetworkException(e);
} catch (e) {
throw Exception(e.toString());
}
}
Exception _getDioNetworkException(DioError dioError) {
final List<DioErrorType> networkExceptions = [
DioErrorType.connectTimeout,
DioErrorType.receiveTimeout,
DioErrorType.sendTimeout,
];
if (networkExceptions.contains(dioError.type)) {
return const MyPipeRemoteException(
"Please check your internet connection");
} else {
final response = dioError.response;
String errorMessage = "Something went wrong...";
if (response != null && response.data != null) {
errorMessage = response.data["message"];
}
return MyPipeRemoteException(errorMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment