Jaguar-dart / client

Contains various packages for client side
46 stars 22 forks source link

Interceptor to change the URL #53

Open jaumard opened 5 years ago

jaumard commented 5 years ago

Hey :)

Just trying to do the following:

class HostInterceptor extends Interceptor {
  final Connectivity _connectivity;
  final PreferencesProvider _preferencesProvider;
  final LocalServerProvider _serverProvider;
  String _host;
  ConnectivityResult _previousConnectivity;
  String _previousWifiIp;

  HostInterceptor({
    Connectivity connectivity,
    LocalServerProvider serverProvider,
    PreferencesProvider preferencesProvider,
  })  : _connectivity = connectivity ?? Connectivity(),
        _serverProvider = serverProvider ?? LocalServerProvider(),
        _preferencesProvider = preferencesProvider ?? PreferencesProvider() {
    if(Platform.isAndroid || Platform.isIOS) {
      _connectivity.onConnectivityChanged.listen((connectivityResult) async {
        if (_previousConnectivity != connectivityResult) {
          _host = null; //reset host to trigger another search on next request
        } else if (connectivityResult == ConnectivityResult.wifi) {
          final ip = await connectivity.getWifiIP();
          if (_previousWifiIp != ip) {
            _host = null; //reset host to trigger another search on next request because we change wifi network
          }
        }

        _previousConnectivity = connectivityResult;
      });
    }
  }

  @override
  FutureOr<void> before(RouteBase route) async {
      final url = route.getUrl;
      final prefExternalUrl = _preferencesProvider.prefs.getString(PreferencesProvider.keyExternalUrl);
          _setExternalUrl(route, url, prefExternalUrl);
    return null;
  }

  _setExternalUrl(RouteBase route, String url, String externalUrl) {
    final urlParts = Uri.parse(url);
    final externalUrlParts = Uri.parse(externalUrl);
    final finalUrl = urlParts.replace(host: externalUrlParts.host, scheme: externalUrlParts.scheme, port: externalUrlParts.port);
    route.url(finalUrl.toString());
  }

  @override
  FutureOr after(StringResponse response) {
    return response;
  }
}

Problem is that it duplicate the path where it shouldn't.

Example:

url on the route is: http://localhost/api/v1/test external url on pref is: http://myDomain.com so finalUrl become: http://myDomain.com/api/v1/test

But the url fails because jaguar actually does the request to: http://myDomain.com/api/v1/test/api/v1/test

Didn't find out why :/

tejainece commented 5 years ago

I will take a look.

droplet-js commented 5 years ago

It's best to be like okhttp Interceptor