Skip to content

Instantly share code, notes, and snippets.

@sahildev001
Created January 24, 2024 10:45
Show Gist options
  • Save sahildev001/befb05f904fef97fe9791ca4f3246086 to your computer and use it in GitHub Desktop.
Save sahildev001/befb05f904fef97fe9791ca4f3246086 to your computer and use it in GitHub Desktop.
caeate interceptor in flutter
class Injector {
static final Injector _singleton = new Injector._internal();
static final dio = Dio();
factory Injector() {
return _singleton;
}
Injector._internal();
RestApiClient getClient() {
// dio.options.connectTimeout = 10000;
// dio.options.receiveTimeout = 3000;
dio.options.baseUrl = ApiService.baseurl;
dio.options.followRedirects = false;
dio.options.headers["Content-Type"] = "application/json";
String token = UserPrefs().getLoggedIUserToken();
if (token != "") {
HopLogs.printInfo(filename: "injector:: 1 ", info: "token=" + token);
dio.options.headers["Authorization"] = token;
dio.options.headers["Content-Type"] = "application/json";
}
dio.interceptors.clear();
final client = RestApiClient(dio);
dio.interceptors.add(new LoggingInterceptors(client: client));
return client;
}
}
class LoggingInterceptors extends Interceptor {
final RestApiClient client;
LoggingInterceptors({required this.client});
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async{
HopLogs.printInfo(filename: "injector:: 2", info :'REQUEST[${options.method}] => PATH: ${options.baseUrl}${options.path}');
options.headers.forEach((k, v) => HopLogs.printInfo(filename: "injector:: ", info :'$k: $v'));
HopLogs.printInfo(filename: "injector:: 3", info : "queryParameters:");
options.queryParameters.forEach((k, v) => HopLogs.printInfo(filename: "injector:: ", info :'$k: $v',));
if (options.data != null) {
HopLogs.printInfo(filename: "injector:: 4", info:"Body: ${options.data}");
}
HopLogs.printInfo(filename: "injector:: 5", info:
"--> END ${options.method != null? options.method.toUpperCase() : 'METHOD'}",);
super.onRequest(options, handler);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
HopLogs.printError(filename: "injector:: 6", error:
'ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
// Reset the request status after completion
super.onError(err, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) async{
HopLogs.printInfo(filename: "injector:: 7", info: 'RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
HopLogs.printInfo(filename: "injector:: 8", info: "Headers:");
response.headers.forEach((k, v) => HopLogs.printInfo(filename: "injector:: ", info: '$k: $v'));
try {
var data = response.data;
HopLogs.printInfo(filename: "injector:: 9", info: "Response: ${jsonEncode(data)}");
if (data is Map && data.containsKey("code") && data["code"] == 401 &&(response.requestOptions.path != ApiService.refreshConst)) {
await _handle401Error(response, handler);
}
super.onResponse(response, handler);
} catch (e) {
HopLogs.printError(filename:'injector:: 10',error: e);
// Handle response parsing errors
}
}
Future<void> _handle401Error(Response response, ResponseInterceptorHandler handler) async {
try {
HopLogs.printInfo(filename: "injector:: 11", info: "Handling 401 Unauthorized error - Retry");
// Call the function to refresh the token
RefreshResponseModel value = await client.doRefreshonSessionExpire();
if (value.code == 200 && value.data != null) {
await UserPrefs().setString(AppUserPrefKeys.token, "Bearer ${value.data ?? ""}");
await _retryFunction(response, handler);
}
} catch (error) {
// Handle the retry error, if needed
HopLogs.printError(filename: "injector:: 12", error: "Error during retry: $error");
onResponse(response, handler);
}
}
Future<void> _retryFunction(Response response,ResponseInterceptorHandler handler ) async {
try {
HopLogs.printInfo(filename: "injector:: 13", info: "Retrying the function...");
// Create a new Options object with updated headers or other parameters
Options newOptions = Options(
method: response.requestOptions.method,
headers: {'Authorization': UserPrefs().getLoggedIUserToken()},
);
// Make the retry request
Response retryResponse = await Injector.dio.request(
response.requestOptions.path,
options: newOptions,
data: response.requestOptions.data,
queryParameters: response.requestOptions.queryParameters,
cancelToken: response.requestOptions.cancelToken,
onSendProgress: response.requestOptions.onSendProgress,
onReceiveProgress: response.requestOptions.onReceiveProgress
);
// Handle the retry response as needed
onResponse(retryResponse, handler); // Pass a dummy handler since it's not used in onResponse
} catch (error) {
// Handle the retry error, if needed
HopLogs.printError(filename: "injector:: 14", error: "Error during retry: $error");
onResponse(response, handler);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment