CodingAleCR / http_interceptor

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

Feature Request: Query Parameters #2

Closed CodingAleCR closed 4 years ago

CodingAleCR commented 5 years ago

Right now you have to do some funky stuff in order to use query parameters when doing a 'get' request. An example would be:

class WeatherRepository {
  Client client = HttpClientWithInterceptor.build(interceptors: [
      WeatherApiInterceptor(),
  ]);

  Future<Map<String, dynamic>> fetchCityWeather(int id) async {
    var parsedWeather;
    try {
      final response = await client.get("$baseUrl/weather?id=$id");
      if (response.statusCode == 200) {
        parsedWeather = json.decode(response.body);
      } else {
        throw Exception("Error while fetching. \n ${response.body}");
      }
    } catch (e) {
      print(e);
    }
    return parsedWeather;
  }
}

class WeatherApiInterceptor implements InterceptorContract {
  @override
  Future<RequestData> interceptRequest({RequestData data}) async {
    try {
      data.url = "${data.url}&appid=$OPEN_WEATHER_API_KEY";
      data.url = "${data.url}&units=metric";
      data.headers["Content-Type"] = "application/json";
    } catch (e) {
      print(e);
    }
    return data;
  }

  @override
  Future<ResponseData> interceptResponse({ResponseData data}) async => data;
}

This is a big problem mainly because if you do not add the '?' to your URL in the repository then most the interception could fail to add the proper parameters resulting in an URL like so:

'$baseUrl/weather&appid=$appid&units=metric'

Instead of the desired:

'$baseUrl/weather?appid=$appid&units=metric'