Skip to content

Instantly share code, notes, and snippets.

@Sorbh
Created March 4, 2022 11:52
Show Gist options
  • Save Sorbh/fc5ccaba807712db6414f20b82c3ebf7 to your computer and use it in GitHub Desktop.
Save Sorbh/fc5ccaba807712db6414f20b82c3ebf7 to your computer and use it in GitHub Desktop.
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_disposable.dart';
enum Method { POST, GET, PUT, DELETE, PATCH }
const BASE_URL = "https://hris.sslwireless.com/api/v1/";
class RestClient extends GetxService {
late Dio _dio;
//this is for header
static header() => {
'Content-Type': 'application/json',
};
Future<RestClient> init() async {
_dio = Dio(BaseOptions(baseUrl: BASE_URL, headers: header()));
initInterceptors();
return this;
}
void initInterceptors() {
_dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
print('REQUEST[${options.method}] => PATH: ${options.path} '
'=> Request Values: ${options.queryParameters}, => HEADERS: ${options.headers}');
return handler.next(options);
}, onResponse: (response, handler) {
print('RESPONSE[${response.statusCode}] => DATA: ${response.data}');
return handler.next(response);
}, onError: (err, handler) {
print('ERROR[${err.response?.statusCode}]');
return handler.next(err);
}));
}
Future<dynamic> request(
String url, Method method, Map<String, dynamic>? params) async {
Response response;
try {
if (method == Method.POST) {
response = await _dio.post(url, data: params);
} else if (method == Method.DELETE) {
response = await _dio.delete(url);
} else if (method == Method.PATCH) {
response = await _dio.patch(url);
} else {
response = await _dio.get(
url,
queryParameters: params,
);
}
if (response.statusCode == 200) {
return response;
} else if (response.statusCode == 401) {
throw Exception("Unauthorized");
} else if (response.statusCode == 500) {
throw Exception("Server Error");
} else {
throw Exception("Something Went Wrong");
}
} on SocketException catch(e) {
throw Exception("No Internet Connection");
} on FormatException {
throw Exception("Bad Response Format!");
} on DioError catch (e){
throw Exception(e);
} catch (e) {
throw Exception("Something Went Wrong");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment