Skip to content

Instantly share code, notes, and snippets.

@naimurhasan
Created December 20, 2021 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naimurhasan/86f3998326e5ba86f274c8b7f4968b8b to your computer and use it in GitHub Desktop.
Save naimurhasan/86f3998326e5ba86f274c8b7f4968b8b to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
enum RetryResponseStatus {authFailed, success, unknownError, serverError}
class MRetryResponse{
final http.Response response;
final RetryResponseStatus status;
MRetryResponse(this.response, {this.status : RetryResponseStatus.unknownError,});
bool get isSuccess => status == RetryResponseStatus.success;
String get message {
switch(status){
case RetryResponseStatus.success:
return "Success";
break;
case RetryResponseStatus.authFailed:
return "Error: Please log out and login again";
break;
case RetryResponseStatus.serverError:
return "Error: Server problem, please try later";
break;
case RetryResponseStatus.unknownError:
default:
return "Error: Please check your internet";
}
}
}
class RetryRequest{
static Future<MRetryResponse> retryOnFailure(Function(String authKey) theRequest) async {
try{
// call the method
SharedPreferences prefs = await SharedPreferences.getInstance();
final token = prefs.getString("key");
final http.Response currentResponse = await theRequest(token);
print('retry auth got response');
print(currentResponse.statusCode);
print(currentResponse.body);
if(currentResponse.statusCode == 401){
/// request failed please refresh token
print('request failed refreshing token');
String baseUrl = 'https://api.ebook.com.bd/v1/auth';
String url = "${baseUrl}/token/refresh/";
final refreshToken = prefs.getString("Rkey");
http.Response refreshResponse = await http.post(
Uri.parse(url),
body: {
"refresh": refreshToken,
},
);
print('refreshResponse ${refreshResponse.body}');
if (refreshResponse.statusCode == 200) {
print('refreshResponse success');
/// refresh token
var data = jsonDecode(refreshResponse.body);
final newKey = data['access'];
final refreshKey = data['refresh'];
print('refresh data access $newKey');
print('refresh data refresh $refreshKey}');
if(newKey!= null){
await prefs.setString("key", newKey);
await prefs.setString("Rkey", refreshKey);
}
/// the currentResponse
final http.Response currentResponse = await theRequest(newKey);
if(currentResponse.statusCode == 401){
print('second time 401');
/// second time 401
return MRetryResponse(currentResponse, status: RetryResponseStatus.authFailed,);
}else if(currentResponse.statusCode>=500 && currentResponse.statusCode<599){
/// server error with refresh token
return MRetryResponse(currentResponse, status: RetryResponseStatus.serverError);
}else{
/// success in second try
return MRetryResponse(currentResponse, status: RetryResponseStatus.success);
}
}else{
return MRetryResponse(currentResponse, status: RetryResponseStatus.authFailed);
}
}else if(currentResponse.statusCode>=500 && currentResponse.statusCode<599) {
/// server error
return MRetryResponse(currentResponse, status: RetryResponseStatus.serverError);
}else{
/// success in one try
return MRetryResponse(currentResponse, status: RetryResponseStatus.success);
}
}catch(err, stacktrace){
print('Custom Http Retry Auth Error');
print('$err');
print(stacktrace);
return MRetryResponse(null, status: RetryResponseStatus.unknownError);
}
}
}
@naimurhasan
Copy link
Author

USAGE EXAMPLE

Map requestBody = {
      "question": "$questionId",
      "type": errorCause,
 };

Future<http.Response> sendReport(String token) async{
        print('sendReport got Token $token');
        return await http.post(
          Uri.parse(endpoint),
          body: json.encode(requestBody),
          headers: {
            "Authorization": "Bearer " + token,
            "Content-Type": "application/json"
          },
        );
      }
      MRetryResponse mRetryResponse = await RetryRequest.retryOnFailure(sendReport);
      if(mRetryResponse.isSuccess){
        print('success error reporting');
        print(mRetryResponse.response.body);
        apiStatus = {"status": true, "message": "Submitted"};
        return apiStatus;
      }else{
        return apiStatus = {"status": false, "message": mRetryResponse.message};
     }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment