http icon indicating copy to clipboard operation
http copied to clipboard

support for Interceptor

Open beamAkshay opened this issue 2 years ago • 5 comments

beamAkshay avatar Jun 02 '22 09:06 beamAkshay

Hi - can you add a few more details about your request? What the feature would look like, how it might change the API, and example from a library in another language...? Thanks!

devoncarew avatar Jun 06 '22 19:06 devoncarew

Interceptor feature like dio package has because I want to refresh token when it is expired. and I did not find any way to do that in this package. but using Interceptor we can do that easily.

beamAkshay avatar Jun 07 '22 04:06 beamAkshay

Thanks!

For posterity, here's a link to more info: https://pub.dev/packages/dio#interceptors.

And in-lined:

... interceptors, by which we can intercept requests 、 responses and errors before they are handled by then or catchError

devoncarew avatar Jun 09 '22 20:06 devoncarew

If you are familiar with Decorator pattern you can simply do your own interceptors like this:

import 'dart:async';

import 'package:http/http.dart' as http;

typedef GetAccessToken = Future<String?> Function();

class AuthClient extends http.BaseClient {
  AuthClient({
    required this.getAccessToken,
  });

  final _client = http.Client();
  final GetAccessToken getAccessToken;

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    if (request.headers['authorization'] == null) {
      // add authorization header if it isn't exists
      final accessToken = await getAccessToken();
      if (accessToken != null) {
        request.headers['authorization'] = 'Bearer $accessToken';
      }
    }

    return _client.send(request);
  }

  @override
  void close() {
    _client.close();

    super.close();
  }
}

maRci002 avatar Jun 20 '22 19:06 maRci002

we also need a Interceptor to log request send and response, any good approach to added a Interceptor using this library?

coolRoger avatar Mar 19 '24 07:03 coolRoger