CodingAleCR / http_interceptor

A lightweight, simple plugin that allows you to intercept request and response objects and modify them if desired.
MIT License
133 stars 68 forks source link

How should i handle shouldInterceptRequest when you have interceptRequest #136

Closed charlo2433 closed 7 months ago

charlo2433 commented 1 year ago

Do you have a question regarding how to use the plugin? Please describe. A clear and concise description of what the question is. Ex. How do I retry a request? [...]

  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async{
     try {
      var token = await GetStorage().read('token');
      request.headers["Content-type"] = "application/json";
      request.headers["Accept"] = "application/json";
      request.headers["Authorization"] = "Bearer " + token;
    } catch (e) {
      print(e);
    }

    return request;
  }

  @override
  Future<bool> shouldInterceptRequest() {
    // TODO: implement shouldInterceptRequest

   throw true;
  }
CodingAleCR commented 7 months ago

In your comment, you are using throw true which means that shouldInterceptRequest fails because of that. Ideally, you'd want to have the interceptor method and that's it:

  @override
  Future<BaseRequest> interceptRequest({required BaseRequest request}) async{
     try {
      var token = await GetStorage().read('token');
      request.headers["Content-type"] = "application/json";
      request.headers["Accept"] = "application/json";
      request.headers["Authorization"] = "Bearer " + token;
    } catch (e) {
      print(e);
    }

    return request;
  }

By default, the implementation of shouldInterceptRequest looks like this:

Future<bool> shouldInterceptRequest() async => true;

So generally speaking, it's not necessary to modify it if you want to intercept all requests.